如何将pandas数据透视表转换为JSON

时间:2017-09-28 07:28:42

标签: python pandas pivot-table

我使用pandas pivot table创建了一个如下表格。

print(pd_pivot_table)

category_id  name
3            name3        0.329204
24           name24       0.323727
31           name31       0.319526
19           name19       0.008992
23           name23       0.005897

我想基于此pivot_table创建JSON,但我不知道如何。

[
  {
    "category_id": 3,
    "name": "name3",
    "score": 0.329204
  },
  {
    "category_id": 24,
    "name": "name24",
    "score": 0.323727
  },
  {
    "category_id": 31,
    "name": "name31",
    "score": 0.319526
  },
  {
    "category_id": 19,
    "name": "name19",
    "score": 0.008992
  },
  {
    "category_id": 23,
    "name": "name23",
    "score": 0.005897
  }
]

或者,我不知道如何首先获取category_id和name值。 即使您编写下面的代码,也无法获得所需的结果。

for data in pd_pivot_table:
  print(data) # 0.329204
  print(data["category_id"]) # *** IndexError: invalid index to scalar variable.

1 个答案:

答案 0 :(得分:2)

您可以先DataFrame使用print (df) category_id name 3 name3 0.329204 24 name24 0.323727 31 name31 0.319526 19 name19 0.008992 23 name23 0.005897 Name: score, dtype: float64 print (type(df)) <class 'pandas.core.series.Series'> json = df.reset_index().to_json(orient='records') print (json) [{"category_id":3,"name":"name3","score":0.329204}, {"category_id":24,"name":"name24","score":0.323727}, {"category_id":31,"name":"name31","score":0.319526}, {"category_id":19,"name":"name19","score":0.008992}, {"category_id":23,"name":"name23","score":0.005897}] ,然后Series.reset_index再使用<{p}}:

df.reset_index().to_json('file.json',orient='records')

如果需要输出到文件:

print (df.reset_index())
   category_id    name     score
0            3   name3  0.329204
1           24  name24  0.323727
2           31  name31  0.319526
3           19  name19  0.008992
4           23  name23  0.005897

print (type(df.reset_index()))
<class 'pandas.core.frame.DataFrame'>

<强>详情:

@RequestMapping(value = {"/channel-detail"}, method = RequestMethod.GET)