我有一个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}}
答案 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
}
}