I have a list of dicts. Some of the objects in these dicts are dicts themselves. I would like to turn this into a dataframe. This is what I currently get.
In[163]:
res = [{'A':1,'B':{'C':3,'D':4}},{'A':5,'B':{'C':7,'D':8}}]
pd.DataFrame(res)
Out[163]:
A B
0 1 {u'C': 3, u'D': 4}
1 5 {u'C': 7, u'D': 8}
This is what I want:
A BC BD
0 1 3 4
1 5 7 8
I don't really care about the column header names. They can be whatever.
import pandas as pd
res = [{'A':1,'B':{'C':3,'D':4}},{'A':5,'B':{'C':7,'D':8}}]
df = pd.DataFrame(res)
def col2frame(col):
try:
res = pd.DataFrame.from_records(col)
res.columns = [col.name+name for name in res.columns]
return res
except TypeError:
return col
df = pd.concat([col2frame(df[col]) for col in df], axis=1)
print(df)
yields
A BC BD
0 1 3 4
1 5 7 8
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.