【问题标题】:convert pandas dataframe to json with columns as key将 pandas 数据框转换为以列为键的 json
【发布时间】:2019-07-27 01:10:31
【问题描述】:

我有一个这样的数据框:

df:
Col1    col2    col3    col4
 A       1        2       3
 A       4        5       6
 A       7        8       9
 B       3        2       1
 B       4        4       4

我想为每个 col1 值创建一个嵌套的 json 文件,里面会有 col2、col3、col4 作为键和这些列的值,

输出应如下所示:

{
"col1": A,
"Other_details": {
    "col2": 1,
    "col3": 2,
    "col4": 3
},{
    "col2": 4,
    "col3": 5,
    "col4": 6
},{
    "col2": 7,
    "col3": 8,
    "col4": 9
},
},
{
"col1": B,
"Other_details": {
    "col2": 3,
    "col3": 2,
    "col4": 1
},{
    "col2": 4,
    "col3": 4,
    "col4": 4
}
}

如何做到最有效的方式

【问题讨论】:

    标签: python json pandas dataframe


    【解决方案1】:

    使用DataFrame.groupbyDataFrame.applyDataFrame.to_dict 所有没有Col1 的列由Index.difference 过滤,由DataFrame.reset_index 创建DataFrame,最后使用DataFrame.to_dict 用于字典输出或DataFrame.to_json json 输出:

    cols = df.columns.difference(['Col1'])
    d = (df.groupby('Col1')[cols]
            .apply(lambda x: x.to_dict('r'))
            .reset_index(name='Other_details')
            .to_dict(orient='records'))
    

    cols = df.columns.difference(['Col1'])
    d = (df.groupby('Col1')[cols]
            .apply(lambda x: x.to_dict('r'))
            .reset_index(name='Other_details')
            .to_json(orient='records'))
    

    【讨论】:

      猜你喜欢
      • 2020-09-02
      • 2021-02-09
      • 2019-05-14
      • 2019-07-01
      • 2021-12-13
      • 2017-05-03
      • 2021-09-27
      • 1970-01-01
      • 2018-03-25
      相关资源
      最近更新 更多