【问题标题】:AttributeError: 'NoneType' object has no attribute 'items' when iterating over the rows of the listAttributeError:“NoneType”对象在迭代列表的行时没有属性“items”
【发布时间】:2018-10-07 18:07:31
【问题描述】:

我的数据是 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' object has no attribute 'items' on the line

对于 content.items() 中的键、值:

我了解出现此问题是因为内容数据中没有类型。有什么方法可以忽略这个错误或任何解决方案只返回非无值?

预期输出(DataFrame 格式)

【问题讨论】:

  • 可能会将样本数据减少到与您的问题相关的内容。当前样本似乎包含不相关但不完整的数据以使其可重现。
  • 我已经编辑了示例数据并清楚地提供了预期的输出。我的代码需要将内容字典拆分为数据框中的每个键的单独列,索引为“c_”作为列名,如预期的输出图片所示。
  • 第四行应该是for content in data['contents']:而不是for content in row['contents']:
  • 它给了我一个 TypeError: list indices must be integers or slices, not str @Stack.
  • 您的理解中可能有一个小错字或错误。尝试使用 pdb 逐行执行代码。参见例如pythonconquerstheuniverse.wordpress.com/2009/09/10/… 用其他相对简单的代码解决问题的最简单方法是学习调试实践。如果您希望成为 dict 的某个变量结果为 None,这就是您需要逐步检查代码并找出哪个部分没有按照您的预期执行的线索。

标签: python pandas attributeerror nonetype


【解决方案1】:
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'}]}

除了从 dict 创建 DataFrame 之外,您还不清楚您要做什么,这可以通过以下代码完成:

df = pd.DataFrame.from_dict(data)

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

【讨论】:

    猜你喜欢
    • 2023-03-16
    • 2017-12-16
    • 2015-11-14
    • 2013-09-22
    • 2020-07-22
    • 2015-09-30
    • 2020-09-22
    • 2014-09-14
    • 2019-01-01
    相关资源
    最近更新 更多