嵌套JSON到数据帧

2024-06-14 04:46:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将嵌套的json扩展到pandas dataframe,但是提供的解决方案对我不起作用。你知道吗

我的情况是:

我在MongoDB中有json数据。你知道吗

当我连接到这个数据库时,它工作得很好,但问题是当我需要将嵌套的json扩展到dataframes时,因为在有些列中我有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)

提前谢谢。你知道吗


Tags: 数据nameidjsoncityindexcountrydocuments
2条回答

你试过了吗。你知道吗

df["location"].apply(pd.Series)

用途:

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) 

相关问题 更多 >