Userdefined Json Format From Pandas DataFrame

后端 未结 1 1221
花落未央
花落未央 2021-01-15 11:20

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

country     branch      no_of_employee     total_salary    count_D         


        
1条回答
  •  时光说笑
    2021-01-15 11:50

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

    0 讨论(0)
提交回复
热议问题