【问题标题】:Convert Pandas Series to Dictionary Without Index将 Pandas 系列转换为没有索引的字典
【发布时间】:2020-06-23 15:26:09
【问题描述】:

我需要将 Pandas 系列转换为没有索引的字典(如 pandas.DataFrame.to_dict('r')) - 代码如下:

grouped_df = df.groupby(index_column)
for key, val in tqdm(grouped):
    json_dict[key] = val.apply(lambda x: x.to_dict(), axis=1).to_dict()

目前,我得到如下输出:

{
   "15717":{
      "col1":1.61,
      "col2":1.53,
      "col3":1.0
   },
   "15718":{
      "col1":10.97,
      "col2":5.79,
      "col3":2.0
   },
   "15719":{
      "col1":15.38,
      "col2":12.81,
      "col3":1.0
   }
}

但我需要如下输出:

[
   {
      "col1":1.61,
      "col2":1.53,
      "col3":1.0
   },
   {
      "col1":10.97,
      "col2":5.79,
      "col3":2.0
   },
   {
      "col1":15.38,
      "col2":12.81,
      "col3":1.0
   }
]

感谢您的帮助!

编辑:这是原始数据框:

        col1   col2 col3
2751    5.46    1.0 1.11
2752    16.47   0.0 6.54
2753    26.51   0.0 18.25
2754    31.04   1.0 28.95
2755    36.45   0.0 32.91

【问题讨论】:

  • 能否请您添加原始数据框,以便重现您的场景?

标签: python json pandas dictionary


【解决方案1】:

两种方法:

[v for _, v in df.to_dict(orient="index").items()]

另一个:

df.to_dict(orient="records")

无论哪种方式,输出都是:

[{'col1': 1.61, 'col2': 1.53, 'col3': 1.0},
 {'col1': 10.97, 'col2': 5.79, 'col3': 2.0},
 {'col1': 15.38, 'col2': 12.81, 'col3': 1.0}]

【讨论】:

    【解决方案2】:

    你可以试试:

    df.T.to_dict('r')
    

    输出:

    [{'col1': 1.61, 'col2': 1.53, 'col3': 1.0},
     {'col1': 10.97, 'col2': 5.79, 'col3': 2.0},
     {'col1': 15.38, 'col2': 12.81, 'col3': 1.0}]
    

    【讨论】:

      猜你喜欢
      • 2018-02-02
      • 2022-01-07
      • 2022-10-06
      • 2019-09-26
      • 2020-09-08
      • 2019-05-04
      • 1970-01-01
      • 1970-01-01
      • 2018-06-03
      相关资源
      最近更新 更多