将字典列表转换为Pandas DataFrame

本文翻译自:Convert list of dictionaries to a pandas DataFrame

I have a list of dictionaries like this: 我有这样的词典列表:

[{'points': 50, 'time': '5:00', 'year': 2010}, 
{'points': 25, 'time': '6:00', 'month': "february"}, 
{'points':90, 'time': '9:00', 'month': 'january'}, 
{'points_h1':20, 'month': 'june'}]

And I want to turn this into a pandas DataFrame like this: 我想把它变成这样的pandas DataFrame

      month  points  points_h1  time  year
0       NaN      50        NaN  5:00  2010
1  february      25        NaN  6:00   NaN
2   january      90        NaN  9:00   NaN
3      june     NaN         20   NaN   NaN

Note: Order of the columns does not matter. 注意:列的顺序无关紧要。

How can I turn the list of dictionaries into a pandas DataFrame as shown above? 如何将字典列表转换为如上所述的pandas DataFrame?


#1楼

参考:https://stackoom.com/question/1Oat4/将字典列表转换为Pandas-DataFrame


#2楼

假设d是您的字典列表,简单地:

pd.DataFrame(d)

#3楼

在熊猫16.2中,我必须执行pd.DataFrame.from_records(d)才能使其正常工作。


#4楼

You can also use pd.DataFrame.from_dict(d) as : 您还可以将pd.DataFrame.from_dict(d)用作:

In [8]: d = [{'points': 50, 'time': '5:00', 'year': 2010}, 
   ...: {'points': 25, 'time': '6:00', 'month': "february"}, 
   ...: {'points':90, 'time': '9:00', 'month': 'january'}, 
   ...: {'points_h1':20, 'month': 'june'}]

In [12]: pd.DataFrame.from_dict(d)
Out[12]: 
      month  points  points_h1  time    year
0       NaN    50.0        NaN  5:00  2010.0
1  february    25.0        NaN  6:00     NaN
2   january    90.0        NaN  9:00     NaN
3      june     NaN       20.0   NaN     NaN

#5楼

How do I convert a list of dictionaries to a pandas DataFrame? 如何将字典列表转换为Pandas DataFrame?

The other answers are correct, but not much has been explained in terms of advantages and limitations of these methods. 其他答案是正确的,但是就这些方法的优点和局限性而言,并没有太多解释。 The aim of this post will be to show examples of these methods under different situations, discuss when to use (and when not to use), and suggest alternatives. 这篇文章的目的是展示在不同情况下这些方法的示例,讨论何时使用(何时不使用),并提出替代方案。 <

  • 7
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值