python - 来自 Pandas DataFrame 的用户定义的 Json 格式

标签 python json pandas dataframe

我有一个 pandas dataFrame。打印 pandas DataFrame 后,结果如下所示

country     branch      no_of_employee     total_salary    count_DOB   count_email
  x            a            30                 2500000        20            25
  x            b            20                 350000         15            20
  y            c            30                 4500000        30            30
  z            d            40                 5500000        40            40
  z            e            10                 1000000        10            10
  z            f            15                 1500000        15            15

我想将其转换为用户定义的用户格式,例如

    {
      "x": [
        {
          "Branch": "a",
          "no_employee": 30
        },
        {
          "Branch": "b",
          "no_employee": 20
        }

      ],
      "y": [
         {
          "Branch": "c",
          "no_employee": 30
        },
        {
          "Branch": "d",
          "no_employee": 40
        }

      ],
      "z": [
         {
          "Branch": "d",
          "no_employee": 40
        },
        {
          "Branch": "e",
          "no_employee": 10
        },
        {
          "Branch": "f",
          "no_employee": 15
        }

  ]

}

如何将此数据帧转换为这种格式

最佳答案

您可以尝试groupbyapply to_dict最后to_json :

g = df.groupby('country')[["branch", "no_of_employee"]]
                                                .apply(lambda x: x.to_dict(orient='records'))
print g.to_json()

{
    "x": [{
        "no_of_employee": 30,
        "branch": "a"
    }, {
        "no_of_employee": 20,
        "branch": "b"
    }],
    "y": [{
        "no_of_employee": 30,
        "branch": "c"
    }],
    "z": [{
        "no_of_employee": 40,
        "branch": "d"
    }, {
        "no_of_employee": 10,
        "branch": "e"
    }, {
        "no_of_employee": 15,
        "branch": "f"
    }]
}

关于python - 来自 Pandas DataFrame 的用户定义的 Json 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35698067/

相关文章:

python - 将 Header 和 Dataframe 放入新的 CSV 中

python - 使用 MNIST 训练模型的 Tensorflow 总是打印错误的数字

javascript - ajax url 选项可以采用一组 url 而不是仅一个

python - 数据框分组和排序

python - 堆垛和卸垛

python - 在Django中对要请求的图片进行排队

python - 根据文档,PyGAD 未接收整数参数

c# - 从 mailchimp campaignEmailStatsAIMAll 使用 C# 中的 JSON

json - 使用来自 Google Earth Engine 中图像集合中每个单独图像的波段的值填充 FeatureCollection

python - 将数据框列数据分类为拉丁/非拉丁