如何以特定格式将pandas数据框导出到json

问题描述 投票:1回答:1

我的数据框是

  'col1' , 'col2'
    A    ,   89
    A    ,   232
    C    ,   545
    D    ,   998

并希望出口如下:

{
  'A' : [ 89, 232 ],
  'C' : [545],
  'D' : [998]   
}

但是,所有to_json都不适合这种格式(orient ='records',...)。有没有办法像这样输出?

json pandas dataframe
1个回答
2
投票

使用groupby转换为list然后to_json

json = df.groupby('col1')['col2'].apply(list).to_json()
print (json)
{"A":[89,232],"C":[545],"D":[998]}

详情:

print (df.groupby('col1')['col2'].apply(list))
col1
A    [89, 232]
C        [545]
D        [998]
Name: col2, dtype: object
© www.soinside.com 2019 - 2024. All rights reserved.