Skip to content Skip to sidebar Skip to footer

Userdefined Json Format From Pandas 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

Solution 1:

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

Post a Comment for "Userdefined Json Format From Pandas Dataframe"