python - 在 JSON 序列化中嵌套一组具有新标头的列
问题描述
我有一个这样的熊猫数据框
start end compDepth compReleaseDepth compMeanRate
0 0.0 0.62 58.0999985 1.5 110
1 0.66 1.34 57.1399994 3 94
2 1.42 2.1 57.1399994 2.5 89
3 2.21 2.87 58.5699997 2.5 79
4 2.97 3.65 55.2399979 3.5 77
5 3.78 4.45 53.8600006 1.5 76
6 4.49 5.17 62.2700005 0.5 81
7 5.97 6.65 56.1899986 2.5 85
我需要将数据序列化为 JSON 并且我使用df.to_json(orient='records')
它并且它工作正常。
但是,我想将最后 3 列嵌套到一个名为"annotations"
. 这就是我想要实现的,有没有简单的方法可以做到这一点?
[{
"start": "0.0",
"end": "0.62",
"annotations": {
"compDepth": "58.0999985",
"compReleaseDepth": "1.5",
"compMeanRate": "110"
}
}, {
"start": "0.66",
"end": "1.34",
"annotations": {
"compDepth": "57.1399994",
"compReleaseDepth": "3",
"compMeanRate": "94"
}
}, {
"start": "1.42",
"end": "2.1",
"annotations": {
"compDepth": "57.1399994",
"compReleaseDepth": "2.5",
"compMeanRate": "89"
}
}, {
"start": "2.21",
"end": "2.87",
"annotations": {
"compDepth": "58.5699997",
"compReleaseDepth": "2.5",
"compMeanRate": "79"
}
},
解决方案
一种简单的方法是将自己的数据嵌套在一个新列中,使用to_dict
df['annotations'] = df[['compDepth','compReleaseDepth','compMeanRate']].to_dict(orient='records')
然后,您to_json(orient='records')
只在最终输出中需要的 3 列上使用
df[['start','end','annotations']].to_json(orient='records')
推荐阅读
- c - 函数返回值时释放 malloc
- flutter - Flutter:日期选择器切换到输入模式?
- dgraph - 如何让 Dgraph uid_in 使用变量输入
- reactjs - 在axios http调用反应后打开引导模式
- html - 如何在不同的.ts文件中单击按钮时调用打字稿方法?
- vuetify.js - 阻止 Vuetify 打印到控制台“[Vuetify] 图像加载失败”
- scala - 如何测试期货是否在Scala中按顺序运行?
- python - 在 Pandas 中按元素和计数对数据框进行分组
- r - 在R中按组计算多列的出现
- sql-server - 使用 mssql 复制的一种方式 DB 同步