将字典列表转换为Dataframe

我有这样的字典列表:

[{'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'}]

我想把它变成一个像这样的熊猫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

注意:列的顺序无关紧要。

最终目标是将其写入文本文件,这似乎是我能找到的最佳解决方案。 如何将字典列表变成如上所示的熊猫数据框?


假设d是你的列表,只需:

pd.DataFrame(d)

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


你也可以使用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
链接地址: http://www.djcxy.com/p/5451.html

上一篇: Convert list of dictionaries to Dataframe

下一篇: Is there a short contains function for lists?