如何创建数据框以生成给定格式的json [英] how to create a dataframe to generate json in the given format

查看:161
本文介绍了如何创建数据框以生成给定格式的json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从数据框中生成一个json,但是我尝试了多种df格式,但仍然无法获得所需的json格式.

I need to generate a json from my dataframe but I have tried many formats of df but still I am not able get the required json format.

我所需的json格式是

My required json format is,

[
    {
        "Keyword": "Red", 
        "values": [
            {
                "value": 5, 
                "TC": "Color"
            }            
        ]
    }, 
     {
        "Keyword": "Orange", 
        "values": [
            {
                "value": 5, 
                "TC": "Color"
            }            
        ]
    }, 
     {
        "Keyword": "Violet", 
        "values": [
            {
                "value": 5, 
                "TC": "Color"
            }            
        ]
    }
]

我想让df生成此json.请帮忙.

I want a df to generate this json. Please help.

但目前我正在获取df.to_json:

but currently im getting df.to_json:

 {"Names":{"0":"Ram","1":"pechi","2":"Sunil","3":" Ravi","4":"sri"},"Values":{"0":"[{'value':2,'TC': 'TC Count'}]","1":"[{'value':2,'TC': 'TC Count'}]","2":"[{'value':1,'TC': 'TC Count'}]","3":"[{'value':1,'TC': 'TC Count'}]","4":"[{'value':1,'TC': 'TC Count'}]"}}  

推荐答案

我认为您需要:

  • set_index for columns not in nested dictionaries
  • create dicts by apply with to_dict
  • reset_index for column from index
  • create json by to_json
print (df)

  Keyword     TC  value
0     Red  Color      5
1  Orange  Color      5
2  Violet  Color      5

j = (df.set_index('Keyword')
        .apply(lambda x: [x.to_dict()], axis=1)
        .reset_index(name='values')
        .to_json(orient='records'))
print (j)

[{"Keyword":"Red","values":[{"TC":"Color","value":5}]},
 {"Keyword":"Orange","values":[{"TC":"Color","value":5}]},
 {"Keyword":"Violet","values":[{"TC":"Color","value":5}]}]

用于写入file:

(df.set_index('Keyword')
   .apply(lambda x: [x.to_dict()], axis=1)
   .reset_index(name='values')
   .to_json('myfile.json', orient='records'))

这篇关于如何创建数据框以生成给定格式的json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆