我正在尝试将嵌套json扩展到pandas数据帧,但提供的解决方案对我不起作用。
我的案例是:
我在MongoDB中有json数据。
当我连接到这个数据库时,它工作得很好,但问题是当我需要将嵌套的json扩展到pandas数据帧时,因为有些列中有json对象。
index id name location
0 0001 George [{'country':'Colombia', 'department': 'Antioquia', 'city': 'Medellin'}]
1 0002 Gilberth [{'country':'Colombia', 'department': 'Antioquia', 'city': 'Medellin'}]
2 0003 Christopher [{'country':'Colombia', 'department': 'Antioquia', 'city': 'Medellin'}]
我需要转换成数据帧,比如:
index id name country department city
0 0001 George Colombia Antioquia Medellin
1 0002 Gilberth Colombia Antioquia Medellin
2 0003 Christopher Colombia Antioquia Medellin
这里我展示了如何读取json数据:
json_documents = list(properties.find({}))
df = pd.DataFrame(json_documents)
df.head(2)
提前谢谢。
使用:
df2=df['location'].apply(lambda x: pd.DataFrame(x))
pd.concat([df[df.columns[:-1]],df2],axis=1)
您也可以尝试json_normalize
from pandas.io.json import json_normalize
df=json_normalize(json_documents)
你试过了吗。
df["location"].apply(pd.Series)