AttributeError:在列表的行上进行迭代时,“ NoneType”对象没有属性“ items”

时间:2018-10-07 18:07:31

标签: python pandas attributeerror nonetype

我的数据为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.'}]

由于键“ contents”包含一个多级字典值的列表,为了将其转换为正确的数据帧,我编写了以下代码。

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 :(得分:0)

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之外,尚不清楚您要做什么,这可以通过以下代码完成:

df = pd.DataFrame.from_dict(data)

enter image description here

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

enter image description here