AttributeError: у объекта 'NoneType' нет атрибута 'items' при итерации по строкам списка - PullRequest
0 голосов
/ 07 октября 2018

Мои данные представлены в формате JSON, и я прочитал их в виде списка.

'contents': [{'content': 'Express', 'mime': 'text/plain', 'type': 'kicker'},
{'content': 'Month of Muscle', 'mime': 'text/plain', 'type': 'title'},
{'content': 'By Vicky Hallett', 'mime': 'text/plain', 'type': 'byline'},
{'content': 1325608933000, 'mime': 'text/plain', 'type': 'date'},
{'content': 'SparkPeople trainer Nicole Nichols asks for only 28 days to get you into shape',
 'mime': 'text/plain',
 'type': 'deck'},
{'fullcaption': 'Nicole Nichols, front, chose backup exercisers with strong but realistic physiques to make the program less intimidating.',
'imageURL': 'http://www.expressnightout.com/wp-content/uploads/2012/01/SparkPeople28DayBootcamp.jpg',
 'mime': 'image/jpeg',
 'imageHeight': 201,
 'imageWidth': 300,
 'type': 'image',
 'blurb': 'Nicole Nichols, front, chose backup exercisers with strong but realistic physiques to make the program less intimidating.'},
{'content': 'If you’ve seen a Nicole Nichols workout before, chances are it 
was on YouTube. The fitness expert, known as just Coach Nicole to the 
millions of members of <a href="http://www.sparkpeople.com" 
target="_blank">SparkPeople.com</a>, has filmed dozens of routines for the 
free health website. The popular videos showcasing her girl-next-door style, 
gentle encouragement and clear cueing have built such a devoted following 
that the American Council on Exercise and Life Fitness just named her 
“America’s top personal trainer to watch.”',
'subtype': 'paragraph',
'type': 'sanitized_html',
'mime': 'text/html'},
{'content': 'But “SparkPeople: 28 Day Boot Camp” ($17, Acacia) is her first 
slickly produced DVD and a chance to bring her fans something beyond the 
quick hits she’s been able to offer online. “We put it all together so you 
get more done in less time. There’s upper body, lower body and cardio 
intervals throughout to elevate the heart rate more,” she says.',
'subtype': 'paragraph',
'type': 'sanitized_html',
'mime': 'text/plain'},
{'content': 'Viewers can choose from four segments, ranging from 12 to 30 
minutes. (The longest one, which is packed with kettlebell-inspired swings 
and lifts, is Nichols’ favorite.) The DVD includes a calendar with a 
suggested plan for how to mix up the workouts, so you’re rarely repeating 
moves. And when you are, Nichols hopes you get comfortable challenging 
yourself with the more difficult modifications — which might mean balancing 
on one leg while you perform that lateral raise or turning a step into a 
jump. “Whatever your level, there is something for you,” she says. “But I 
wanted to give people something to progress to.”',
'subtype': 'paragraph',
'type': 'sanitized_html',
'mime': 'text/plain'},
 {'content': 'One unusual feature of the program is the countdown clock on 
 the screen during each of the segments, reminding you of exactly how much 
 longer you need to sweat it out. “I like to know I’m making progress. I 
 find that motivating,” Nichols says.',
 'subtype': 'paragraph',
 'type': 'sanitized_html',
 'mime': 'text/plain'},
 {'content': 'At the end of the 28 days, which is how long research has 
 shown it takes people to establish a habit, Nichols is certain you’ll see 
 some progress of your own.',
 'subtype': 'paragraph',
 'type': 'sanitized_html',
 'mime': 'text/plain'},
 {'content': 'Stick With It',
'subtype': 'h3',
'type': 'sanitized_html',
'mime': 'text/plain'},
{'content': 'Nichols’ tips for keeping your New Year’s resolution',
'subtype': 'paragraph',
'type': 'sanitized_html',
'mime': 'text/plain'},
'subtype': 'paragraph',
'type': 'sanitized_html',
'mime': 'text/html'},
{'content': '<strong>2. Set your alarm clock earlier.</strong> “Morning 
 workouts work for people for a reason. Nothing else will get in the way, 
and being tired is your only excuse,” she says. Later in the day, you’ll 
find many more reasons you don’t have time.',
'subtype': 'paragraph',
'type': 'sanitized_html',
'mime': 'text/html'},
 {'content': '<strong>3. Prioritize.</strong> When people say they can’t fit 
exercise in their schedule, Nichols always asks, “How much TV do you watch?” 
Use your shows as a reward for your workout instead of the replacement, she 
suggests.',
'subtype': 'paragraph',
'type': 'sanitized_html',
'mime': 'text/html'},
 {'role': '',
'type': 'author_info',
'name': 'Vicky Hallett',
'bio': 'Vicky Hallett is a freelancer and former MisFits columnist.'}]

Поскольку ключ «содержимое» содержит список многоуровневых значений словаря, для преобразования его в правильный фрейм данных я написал следующий код.

new_data = []
for row in data: 
    if 'contents' in row:
        for content in row['contents']:
            new_dict = dict(row)
            del new_dict['contents']
            for key, value in content.items():
                new_dict['c_{}'.format(key)] = value
                new_data.append(new_dict)
    else:
        new_data.append(row)

df = pd.DataFrame(new_data)

Но я получаю AttributeError: у объекта 'NoneType' нет атрибута 'items' в строке

для ключа, значение в content.items ():

Я понимаю, что эта проблема возникает из-за отсутствия типа в данных содержимого.Есть ли способ игнорировать эту ошибку или какое-либо решение для возврата только не-нет значений?

Ожидаемый вывод (в формате DataFrame)

Splitting the contents keys into various columns with index 'c_'

1 Ответ

0 голосов
/ 08 октября 2018
import pandas as pd

data = {'contents': [{'content': 'Express', 'mime': 'text/plain', 'type': 'kicker'},
 {'content': 'Month of Muscle', 'mime': 'text/plain', 'type': 'title'},
 {'content': 'By Vicky Hallett', 'mime': 'text/plain', 'type': 'byline'},
 {'content': 1325608933000, 'mime': 'text/plain', 'type': 'date'},
 {'content': 'SparkPeople trainer Nicole Nichols asks for only 28 days to get you into shape',
 'mime': 'text/plain',
 'type': 'deck'},
 {'fullcaption': 'Nicole Nichols, front, chose backup exercisers with strong but realistic physiques to make the program less intimidating.',
 'imageURL': 'http://www.expressnightout.com/wp-content/uploads/2012/01/SparkPeople28DayBootcamp.jpg',
  'mime': 'image/jpeg',
  'imageHeight': 201,
  'imageWidth': 300,
  'type': 'image',
  'source': 'The Washington Post'}]}

Неясно, что вы пытаетесь сделать, кроме как создать DataFrame из dict, что можно сделать с помощью следующего кода:

df = pd.DataFrame.from_dict(data)

enter image description here

df_new = df['contents'].apply(pd.Series)

enter image description here

...