pandas AttributeError: 'list' 对象在尝试从 dicts 列表创建 DataFrame 时没有属性 'keys'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34831448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 00:31:11  来源:igfitidea点击:

AttributeError: 'list' object has no attribute 'keys' when attempting to create DataFrame from list of dicts

pythonlistdictionarypandasdataframe

提问by Vincent Buscarello

Thanks a ton for any help,

非常感谢您的帮助,

I have a list of dictionaries that I need to put in a data frame. I know the normal method in pandas is

我有一个需要放入数据框中的字典列表。我知道大Pandas的正常方法是

final_df=pd.DataFrame.from_records(Mixed_and_Poured[0], index='year')

where Mixed_and_poured is a list containing another list that actually holds the dictionaries

其中 Mixed_and_poured 是一个列表,其中包含另一个实际保存字典的列表

print Mixed_and_Poured
[[{'Country': 'Brazil', u'Internet users': '2.9', 'Year': '2000'}, {'Country': 'Brazil', u'Internet users': '21', 'Year': '2005'}, {'Country': 'Brazil', u'Internet users': '40.7', 'Year': '2010'}, {'Country': 'Brazil', u'Internet users': '45', 'Year': '2011'}, 

I could swear

我可以发誓

final_df=pd.DataFrame.from_records(Mixed_and_Poured[0], index='year')

was just working!! but when I ran it today it throws

只是工作!但是当我今天运行它时它抛出

AttributeError: 'list' object has no attribute 'keys'

Why is it looking for keys in this list now?

为什么它现在要在这个列表中寻找钥匙?

采纳答案by Vincent Buscarello

So turns out I wasnt actually operating on a list of just dictionaries, there was a little bastard list hiding at the end there.

所以事实证明我实际上并没有在一个字典列表上操作,在那里隐藏着一个小小的混蛋列表。

Sorry ya'll!

对不起你们!

回答by Liam Foley

I can't reproduce your error with the data given, I get a KeyError.

我无法用给定的数据重现您的错误,我收到一个 KeyError。

But why even use from_records?

但是为什么还要使用 from_records 呢?

pd.DataFrame(Mixed_and_Poured[0]).set_index('Year')

Out:

出去:

     Country Internet users
Year                       
2000  Brazil            2.9
2005  Brazil             21
2010  Brazil           40.7
2011  Brazil             45

回答by Daniel

I had this issue as well when a couple of items from a list were unavailable (None). The list was quite large so I didn't notice at first. Easiest quick-fix I used was to make a new list with just the items was None:

当列表中的几个项目不可用(无)时,我也遇到了这个问题。名单很大,所以一开始我没有注意到。我使用的最简单的快速修复方法是创建一个新列表,其中的项目为 None:

list1 = [2,3,4, None, 2]
list1 = [item for item in list1 if item != None]
list1
[2, 3, 4, 2]