将python数据框转换为json格式

时间:2019-10-22 11:41:07

标签: python json dataframe dictionary

我正在尝试将python字典转换为json。
输入数据框如下:

user_id |last_update_time |states| tile                       | update_time | message
11       |1571737828      |S231  |{'Action1': [200, 250, 300],|1571737828   | traffic
                                  'Action2': [150, 200, 400]}
22       |1571737828      |S450  |{'Action1': [100, 150, 400],|1571737828   | traffic
                                  'Action2': [350, 500, 700]}

已经尝试过,但是它没有以预期的json输出格式提供如下所示的所需输出格式

adf = input_df.groupby('user_id').apply(lambda x: x.set_index('message').to_dict(orient='index')).to_dict()   

预期的json输出文件:

{
  11:{ 
           "states": "s123", "last_update_time":111342342342,
           "tile": {
               "Action1": [200, 250, 300],
               "Action2": [150, 200, 400]
                      }, "update_time":111342342342
           },
  22:{ 
           "states": "s124", "last_update_time":1113423442342,
           "tile": {{
               "Action1": [100, 150, 400],
               "Action2": [350, 500, 700]
                      }}, "update_time":1141342342342
           },
"message":"traffic"
}

针对此输出的解决方案确实会对我有所帮助。

2 个答案:

答案 0 :(得分:0)

我会尝试:

await

需要的输出。

答案 1 :(得分:0)

假设id_user是您数据框的索引,则以下行应为您提供预期的结果:

df.to_json("/path/to/myjson.json", orient="index")