列表/字典/列表中的Pandas DataFrame [英] Pandas DataFrame from list/dict/list
本文介绍了列表/字典/列表中的Pandas DataFrame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些这种形式的数据:
I have some data in this form:
a = [{'table': 'a', 'field':['apple', 'pear']},
{'table': 'b', 'field':['grape', 'berry']}]
我想创建一个看起来像这样的数据框:
I want to create a dataframe that looks like this:
field table
0 apple a
1 pear a
2 grape b
3 berry b
当我尝试此操作时:
pd.DataFrame.from_records(a)
我明白了:
field table
0 [apple, pear] a
1 [grape, berry] b
我正在使用循环来重组我的原始数据,但是我认为必须有一个更直接,更简单的方法.
I'm using a loop to restructure my original data, but I think there must be a more straightforward and simpler methid.
推荐答案
您可以使用列表推导连接一系列数据帧,每个数据帧对应a
中的每个字典.
You can use a list comprehension to concatenate a series of dataframes, one for each dictionary in a
.
>>> pd.concat([pd.DataFrame({'table': d['table'], # Per @piRSquared for simplification.
'field': d['field']})
for d in a]).reset_index(drop=True)
field table
0 apple a
1 pear a
2 grape b
3 berry b
这篇关于列表/字典/列表中的Pandas DataFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文