【问题标题】:convert dataframe to nested json将数据框转换为嵌套的 json
【发布时间】:2018-07-26 03:39:46
【问题描述】:

我正在使用

pd.read_sql_query() 

从数据库中获取数据然后使用

to_json(orient='records') 

这是数据框:

(1)
  price_formula_id  premium  product_id  exchange  product_name  product_code   weight  
0            30064      0.0        c001       CME          2018            CL      0.3
1            30064      0.0        c002       CME          2018            CL      0.7

(2)
price_formula_id  premium  product_id  exchange  product_name  product_code   weight  
0            30064      NONE        c001       CME          2018            CL      0.3
1            30064      NONE        c002       CME          2018            CL      0.7

转换成这个阵型。

[{
    "price_formula_id": "30064",
    "premium": "0.0",
    "product_id": "c001",
    "exchange": "CME",
    "product_name": "2018",
    "product_code": "CL",
    "weight": "0.3"
},
{
    "price_formula_id": "30064",
    "premium": "0.0",
    "product_id": "c002",
    "exchange": "CME",
    "product_name": "2018",
    "product_code": "CL",
    "weight": "0.7"
}]

但我真正想要的应该是这样的:

 { 
   "price_formula_id": "30064",
   "premium": "0.0",
   "basket": 
    [
     {"product_id": "c001",
      "exchange": "CME",
      "product_name": "2018",
      "product_code": "CL",
      "weight": "0.3"
     },
     {
      "product_id": "c002",
      "exchange": "CME",
      "product_name": "2018",
      "product_code": "CL",
      "weight": "0.7"
     }
    ]
 }

我需要对相同的信息进行分组,并为其余信息设置一个新的索引“篮子”。 我怎么能成功? 非常感谢。

【问题讨论】:

  • 也发布您的数据框
  • 嗨,刚刚添加。谢谢

标签: python pandas


【解决方案1】:

groupby 与带有to_dict 的自定义函数一起用于由differencereset_index 过滤的所有列,最后将其转换为to_json

cols = df.columns.difference(['price_formula_id','premium'])
j = (df.groupby(['price_formula_id','premium'])[cols]
       .apply(lambda x: x.to_dict('r'))
       .reset_index(name='basket')
       .to_json(orient='records'))
print (j)

[{
    "price_formula_id": 30064,
    "premium": 0.0,
    "basket": [{
            "exchange": "CME",
            "product_code": "CL",
            "product_id": "c001",
            "product_name": 2018,
            "weight": 0.3
        },
        {
            "exchange": "CME",
            "product_code": "CL",
            "product_id": "c002",
            "product_name": 2018,
            "weight": 0.7
        }
    ]
}]

【讨论】:

  • 嗨,谢谢你的评论。但我得到了一个错误,这个方法说:reset_index()得到了一个意外的关键字参数'name'。我检查了 reset_index() 的声明,这没有参数,我应该如何更改它?谢谢
  • @Alex - 您可以尝试将.reset_index(name='basket') 更改为.reset_index().rename(columns={'index':'basket'}),必要时更改重命名值
  • 还有一件事需要问'r'的作用是什么?谢谢@jezrael
  • orient='records'一样是records
  • 它有效,谢谢。但是当我将一列设置为空(如'premium':'')时,它将返回[],我不知道为什么
猜你喜欢
  • 2019-07-08
  • 2017-03-21
  • 2020-12-16
  • 1970-01-01
  • 2019-11-24
  • 1970-01-01
  • 2020-10-18
相关资源
最近更新 更多