将数据帧值转换为特定的json样式格式(字典列表)

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

我是python的新手,无法以json样式格式化输出。

我有一个数据帧df作为

    col1    col2
0   ABC     2429
1   DEF     702
2   XYZ     2912
3   ABC     619
4   XYZ     3106
5   DEF     1511

我想生成一个字典列表,其中输出应该看起来像这样:

[
 {
  "col1":"ABC",
  "col2":[2429,619]
 },
 {
  "col1":"DEF",
  "col2":[702,1511]
 },
 {
  "col1":"XYZ",
  "col2":[2912,3106]
 }
]
python pandas
1个回答
1
投票

你可以通过col1分组,将col2的聚合值放入列表中,最后生成一个JSON:

In [64]: j = df.groupby('col1')['col2'].apply(list).reset_index().to_json(orient='records')

In [65]: j
Out[65]: '[{"col1":"ABC","col2":[2429,619]},{"col1":"DEF","col2":[702,1511]},{"col1":"XYZ","col2":[2912,3106]}]'

使其更好(人性化):

In [66]: print(json.dumps(json.loads(j), indent=2))
[
  {
    "col1": "ABC",
    "col2": [
      2429,
      619
    ]
  },
  {
    "col1": "DEF",
    "col2": [
      702,
      1511
    ]
  },
  {
    "col1": "XYZ",
    "col2": [
      2912,
      3106
    ]
  }
]
© www.soinside.com 2019 - 2024. All rights reserved.