I have a large list of a list of dicts, that I would like to transform into a pandas DataFrame. Below I have made a small example of my variable, but in reallity the outer list is much larger and each of the inner lists has more dictionaries.
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"}]
]
I want a Pandas DataFrame that looks like this:
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
I've tried:
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'}
Is there a way to create an empty DataFrame and then append each inner list?
Or how would I only get the values in the DataFrame and the keys in the Column names?
try this:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.