猿问

将数据框转换为嵌套的json

我在用


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"

     }

    ]

 }

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


慕沐林林
浏览 147回答 1
1回答
随时随地看视频慕课网APP

相关分类

Python
我要回答