python-3.x - 在 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 ?
解决方案
有几种方法可以做到这一点,首先,如果索引匹配,我会在单独的数据帧中读取两个 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
推荐阅读
- python - 在 python selenium 中搜索内部元素似乎不起作用
- prolog - 变量 = 术语复合序言
- android - 避免从 JSON 数组响应中删除重复值
- javascript - 刷新时可能html页面状态中的元素没有改变?
- elasticsearch - Elasticsearch 嵌套布尔查询
- unit-testing - 白盒测试 - 基础覆盖率
- python - 对于新的 linux 用户,在 python 中获取登录名的简单方法是什么?
- javascript - 反应 | 功能组件抛出错误 useState Object(...) is not a function
- sql - 我有两个查询要优化,它们在生产中运行很长时间。我已经使用了表中存在的所有可能的索引。有什么建议么?
- linux - 无法在 Linux Mint 中安装 Jmeter 插件管理器