首页 > 解决方案 > 在 Pandas 中读取嵌套的 json

问题描述

我正在尝试将嵌套的 json 数据读入 pandas 数据框。使用以下代码:

deptdata = json.loads(data)
print(pd.DataFrame(json_normalize(deptdata)))

以下输出:

                           dept                      branchData
0                        Mechanical      [{'branch': 'abc', 'sale': 12}]
1                         Civil          [{'branch': 'xyz', 'sale': 18}]

如果我使用pd.DataFrame(json_normalize(deptdata, record_path="branchData")),我得到

branch       sale
 abc          12
 xyz          18

但我失去了部门的详细信息。如何同时获得 dept 和 branchData 以及 groupby dept 和 branch ?

标签: python-3.xpandaspandas-groupby

解决方案


有几种方法可以做到这一点,首先,如果索引匹配,我会在单独的数据帧中读取两个 json 和 concat。

如果这不起作用,并且您的第一个输入与上面匹配,我们可以使用 pandas 中的一些字符串方法和ast模块literal_eval来将您的字符串对象作为字典读取并解析出来。

from ast import literal eval
df1 = pd.concat([df[['dept']], 
           df['branchData'].replace({'\[' : '', '\]' : ''} 
          ,regex=True).map(literal_eval).apply(pd.Series)],axis=1)

print(df1)

         dept branch  sale
0  Mechanical    abc    12
1       Civil    xyz    18

推荐阅读