python - 如何将熊猫数据框转换为结构独特的嵌套 json
问题描述
我有一个结构如下的DF:
traffic_group app_id key category factors
0 desktop app1 CI html 16.618628
1 desktop app1 CI xhr 35.497082
2 desktop app1 IP html 18.294468
3 desktop app1 IP xhr 30.422464
4 desktop app2 CI html 11.028240
5 desktop app2 CI json 33.548279
6 mobile app1 IP html 12.808367
7 mobile app1 IP image 14.410633
我需要将其输出到以下结构的 json:
{ "desktop": {
app1: [ {
"key": "CI",
"threshold: 1,
"window": 60,
"factors: {
"html" : 16.618628
"xhr" : 35.497082
}
}, {
"key": "IP",
"threshold: 1,
"window": 60,
"factors: {
"html" : 18.294468
"xhr" : 30.422464
}
],
app2: [ {
"key": "CI",
"threshold: 1,
"window": 60,
"factors: {
"html" : 11.028240
"json" : 33.548279
}
}
},
"mobile": {
app1: [ {
"key": "IP",
"threshold: 1,
"window": 60,
"factors: {
"html" : 12.808367
"xhr" : 14.410633
}
]
}
}
结构当然是错综复杂的。
我考虑了以下先前的答案,并试图模仿他们的逻辑无济于事:
任何帮助表示赞赏。请不要只发布解决方案,还要解释您的逻辑。
解决方案
我在输入中看不到嵌套字典的任何“阈值”和“窗口”键。让我们假设它们具有固定值。根据您的输出,您希望(通常)为每个三元组(traffic_group、app_id、key)创建一个不同的嵌套字典。因此,我们需要使用这三个键进行初始 groupby 操作。对于每个组,我们创建嵌套字典:
def create_nested_dicts(df):
return {'key': df['key'].unique()[0], 'threshold': 1, 'window': 60, 'factors': dict(zip(df['category'], df['factors']))}
df = df.groupby(['traffic_group', 'app_id', 'key']).apply(create_nested_dicts)
下一步是将行组合到每个 (traffic_group, app_id) 双峰的列表中,并将它们作为字典返回:
df = df.groupby(['traffic_group', 'app_id']).apply(lambda df: df.tolist())
最后一步是将 转换df
为您的输出。有多种方法可以做到这一点。一个简单的方法如下:
df = df.reset_index().groupby('traffic_group').apply(lambda df: df.values)
output = dict(zip(df.index, [{app_id: val for _, app_id, val in vals} for vals in df.values]))
推荐阅读
- python - GCP AI Platform(统一)Python export_model FailedPrecondition: 400 Exporting artifact in format ``不支持
- bash - 如何计算文件中每一行中某个元素的出现次数(bash)
- r - 为R中向量的重复值分配序列号
- javascript - 如何获取此 api 中的所有 87 个对象
- node.js - 如何在一个目录中 Dockerize 两个 nodejs 应用程序
- typescript - 搜索 Typescript 类的预定义实例
- openedge - 如何获取正在进行的多个项目的最后一个元素?
- java - 我的应用中的 AdMob 直播广告没有展示
- elasticsearch - 弹性:存储“FeatureCollection”类型的 GeoJSON,并进行查询
- powershell - Powershell引发错误 - 内存不足(我认为)