从Pandas DataFrame用户定义的Json格式 [英] Userdefined Json Format From Pandas DataFrame

查看:287
本文介绍了从Pandas DataFrame用户定义的Json格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大熊猫数据框架。打印大熊猫DataFrame后,结果如下所示

I have a pandas dataFrame.After printing the pandas DataFrame the results looks like below

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

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

i would like to convert this into user defined user format like

    {
      "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
        }

  ]

}

如何将此数据格式转换为此格式

How can i convert this dataFrame to this format

推荐答案

您可以尝试 groupby apply to_dict ,最后 to_json

You can try groupby with apply to_dict and last 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"
    }]
}

这篇关于从Pandas DataFrame用户定义的Json格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆