首页 > 解决方案 > 连接来自 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
      }
   }

标签: pythonjsonpandas

解决方案


您可以将数据框转换为字典,而不是将字典组合为一个对象,然后转储到 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
        }
    }
}

推荐阅读