【问题标题】:Userdefined Json Format From Pandas DataFrame来自 Pandas DataFrame 的用户定义的 Json 格式
【发布时间】:2016-06-12 09:42:30
【问题描述】:

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

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
        }

  ]

}

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

【问题讨论】:

    标签: python json pandas dataframe


    【解决方案1】:

    你可以试试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"
        }]
    }
    

    【讨论】:

    • @jezrael no no 我得到了确切的答案。我的意思是我想学习如何编写这个函数,为此我可以获得任何教程链接或其他东西
    • 所以我认为您可以查看tutorial1tutorial2question in SO。但通常它会使编写代码更容易一些,并且编写的代码更干净。
    • 很高兴能帮到你!祝你好运!美好的一天。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-01
    • 2020-01-15
    • 2023-04-06
    • 2021-10-23
    • 1970-01-01
    • 2022-11-29
    相关资源
    最近更新 更多