python - json_normalize 的替代方法,用于展平字典中的列表
问题描述
我有一本字典,其中包含一个需要展平到 0 级的列表。
目前,我正在使用json_normalize
,但是,经过几天的研究,我发现它不处理列表并将其保留在一列中。
是否有另一种方法来展平字典和列表?或者是通过创建函数的唯一可能解决方案?
{
"_id" : 1,
"active" : false,
"labelId" : [
6422
],
"level" : [
{
"active" : true,
"level" : 3,
"actions" : [
{
"active" : true,
"description" : "Testing."
}
]
}
]
}
解决方案
您可以使用json_normalise()
explode()
和apply(pd.Series)
js = {'_id': 1,
'active': False,
'labelId': [6422],
'level': [{'active': True,
'level': 3,
'actions': [{'active': True, 'description': 'Testing.'}]}]}
df = pd.json_normalize(js).explode("labelId").explode("level")
df = df.join(df["level"].apply(pd.Series), rsuffix="_l2").explode("actions")
df = df.join(df["actions"].apply(pd.Series), rsuffix="_l3")
print(df.drop(columns=["level","actions"]).to_string())
输出
_id active labelId active_l2 level_l2 active_l3 description
0 1 False 6422 True 3 True Testing.
重命名前缀
js = {'_id': 1,
'active': False,
'labelId': [6422],
'level': [{'active': True,
'level': 3,
'actions': [{'active': True, 'description': 'Testing.'}]}]}
df = pd.json_normalize(js).explode("labelId").explode("level")
df = df.join(df["level"].apply(pd.Series), rsuffix="_l2").explode("actions")
df = df.join(df["actions"].apply(pd.Series), rsuffix="_l3")
df = df.drop(columns=["level","actions"])
df.rename(columns={c:f"{c.split('_')[1]}_{c.split('_')[0]}" for c in df.columns if "_" in c})
推荐阅读
- python-3.x - 文本数据按摩在python中进行距离计算
- amazon-web-services - AWS kibana/ES 尝试创建策略但获得“授权异常”
- python - Python 检查网络连接
- node.js - Nodejs Https服务器(将证书文件地址放在代码中是否安全)
- java - IntegrationFlow + 2 个条件转换器 + 出站网关
- elm - Elm 中的编译时不变性/属性检查
- javascript - 在 Electron 应用程序的 iframe 中找不到嵌入 PDF 的高度?ScrollHeight 的值错误
- swift - Swift:检查来自同一类的 2 个对象是否具有不同的值?
- javascript - 有没有办法在单击按钮时显示另一个表单,而不是仅在用户仅使用 JS 单击“是”后继续执行默认操作
- java - 通过java递归下载远程HTTP目录