我有一个很大的dicts列表列表,我想将其转换为pandas DataFrame。下面我给我的变量做了一个小例子,但实际上外部列表要大得多,每个内部列表都有更多的字典。
all_meta = [[{"Person":1}, {"trial":2}, {"b-setting":"Off"}],
[{"Person":2}, {"trial":5}, {"b-setting":"Off"}],
[{"Person":2}, {"trial":6}, {"b-setting":"Off"}],
[{"Person":2}, {"trial":7}, {"b-setting":"Off"}, {"ERROR":"error2"}]
]
我想要一个看起来像这样的Pandas DataFrame:
person trial b-setting ERROR
0 1 2 Off None
1 2 5 Off None
2 2 6 Off None
3 2 7 Off error2
我试过了:
In[1]: pd.DataFrame(all_meta)
Out[1]:
0 1 2 3
0 {'Person': 1} {'trial': 2} {'b-setting': 'Off'} None
1 {'Person': 2} {'trial': 5} {'b-setting': 'Off'} None
2 {'Person': 2} {'trial': 6} {'b-setting': 'Off'} None
3 {'Person': 2} {'trial': 7} {'b-setting': 'Off'} {'ERROR': 'error2'}
有没有办法创建一个空的DataFrame,然后附加每个内部列表?
或者我如何只获取DataFrame中的值和列名中的键?
答案 0 :(得分:0)
试试这个:
def merge_dicst(dlist):
d = {}
for x in dlist:
d.update(x)
return d
In [97]: pd.DataFrame([merge_dicst(x) for x in all_meta])
Out[97]:
ERROR Person b-setting trial
0 NaN 1 Off 2
1 NaN 2 Off 5
2 NaN 2 Off 6
3 error2 2 Off 7