简体   繁体   中英

Change Pandas JSON output structure

I have a Pandas DataFrame, that after applying a groupby function

df.groupby(['USER', 'GROUP'])['VALOR'].sum()

outputs this:

USER               GROUP
John Doe           A        201.37
                   B        480.59
                   C       1504.16
John Jones         A        239.95
                   B       1123.39
                   C       1736.05
...

However, when I convert this df to JSON:

df.to_json()

It returns this:

{"["John Doe","A"]":201.37,"["John Doe","B"]":480.59,"["John Doe","C"]":1504.16", "["John Jones","A"]":239.95,"["John Jones","B"]":1123.39,"["John Jones","C"]":1736.05}

Is there a way to output it in this format:

{"John Doe": {"A": 201.37, "B":480.59, "C":1504.16}, "John Jones": {"A": 239.95, "B":1123.39, "C":1736.05}}

Yes, unstack it first.

df.unstack(0).to_json()

{
    "John Doe": {
        "A": 201.37,
        "B": 480.59,
        "C": 1504.16
    },
    "John Jones": {
        "A": 239.95,
        "B": 1123.39,
        "C": 1736.05
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM