更改Pandas JSON输出结构

时间:2018-03-23 16:42:56

标签: python python-3.x pandas dataframe

我有一个Pandas DataFrame,在应用了groupby函数

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

输出:

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

但是,当我将此df转换为JSON时:

df.to_json()

它返回:

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

有没有办法以这种格式输出它:

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

1 个答案:

答案 0 :(得分:3)

是的,首先是unstack

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