python - 连接来自 pd.to_json() 的多个数据帧的 JSON 输出
问题描述
我想组合几个数据帧并写入一个单一的 JSON 文件。
import json
import pandas as pd
df1 = pd.DataFrame({'A': [1, 2, 3], 'B': [10, 11, 12]})
df2 = pd.DataFrame({'C': [1, 2, 3], 'D': [10, 11, 12]})
with open('df1_df2.json', 'w') as js:
for df in [df1, df2]:
df.set_index(df.columns[0], inplace=True)
parsed = json.loads(df.to_json())
print(json.dumps(parsed, indent=4))
>>>
{
"B": {
"1": 10,
"2": 11,
"3": 12
}
}
{
"D": {
"1": 10,
"2": 11,
"3": 12
}
}
由于上述内容不会生成有效的 json 文件,因此我不确定将这些 json 对象写入文件的最佳方法。主键 (df1, df2) 的名称可以是任何名称。我想要的格式是:
{
"df1":{
"B":{
"1":10,
"2":11,
"3":12
}
},
"df2":{
"D":{
"1":10,
"2":11,
"3":12
}
}
解决方案
您可以将数据框转换为字典,而不是将字典组合为一个对象,然后转储到 json
import json
import pandas as pd
df1 = pd.DataFrame({'A': [1, 2, 3], 'B': [10, 11, 12]})
df2 = pd.DataFrame({'C': [1, 2, 3], 'D': [10, 11, 12]})
combined = {"df1": df1.to_dict(), "df2": df2.to_dict()}
print(json.dumps(combined, indent=4))
这会产生:
{
"df1": {
"A": {
"0": 1,
"1": 2,
"2": 3
},
"B": {
"0": 10,
"1": 11,
"2": 12
}
},
"df2": {
"C": {
"0": 1,
"1": 2,
"2": 3
},
"D": {
"0": 10,
"1": 11,
"2": 12
}
}
}
推荐阅读
- c# - 将静态扩展分辨率限制为最窄的匹配签名
- keras - ValueError: name_scope 的名称在尝试在 TF2.0 中构建模型类时必须是字符串
- angular - 如何从组件中的服务方法获取 catchError 消息?
- tensorflow - tensorflow 在 anaconda 提示符下工作,但不在命令提示符下
- oracle - Maximo 的出站集成:物化视图不是合适的选择是否有原因?
- c# - 从字典返回差异
- android - 如何修复按钮中的错误意图和音效?
- django - 502 Bad Gateway nginx/1.14.0 (Ubuntu) digitalocean vps django、nginx 和 gunicorn
- python - 如何在两个数据库之间插入公共字段的值
- django - django 抛出“AppRegistryNotReady:应用程序尚未加载。” 导入视图时