本文翻译自: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. 这篇文章的目的是展示在不同情况下这些方法的示例,讨论何时使用(何时不使用),并提出替代方案。 <