【问题标题】:Converting python dataframe to json format将python数据帧转换为json格式
【发布时间】:2023-03-04 09:32:01
【问题描述】:

我正在尝试将 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"
}

这个输出的解决方案对我很有帮助。

【问题讨论】:

标签: python json dataframe dictionary


【解决方案1】:

假设id_user 是您的数据框的索引,以下行应该会给您预期的结果:

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

【讨论】:

    【解决方案2】:

    我会尝试:

    # you set the the user_id as index
    adf=df.set_index('user_id')
    
    # you convert the dataframe to a dict
    # keys are dataframe indexes (user_id)
    adf.to_dict(orient='index')
    

    输出是期望的。

    【讨论】:

    • 这几乎是我想要的,但在输出的每一行中,它将包含一个键值对“消息”:“流量”。但我只需要一次,这将是在输出整个数据之后,然后是“消息”:“流量”。在所需的输出中,消息只有一次,而不是针对输出的每个数据行。希望这能帮助你理解。
    • 为什么 "message":"traffic" 在每一行中?
    • 这是我收到的输出:``` {'11': {'states': 's123', 'last_update_time': 1571737828, 'tile': "{'Action1': [ 200, 250, 300], 'Action2': [150, 200, 400]}", 'update_time': 1571737828, '消息': '交通'}, '22': {'states': 's124', ' last_update_time': 1571737828, 'tile': "{'Action1': [100, 150, 400], 'Action2': [350, 500, 700]}", 'update_time': 1571737828, 'message': '交通' } }
    • 但是期待这个:{'11': {'states': 's123', 'last_update_time': 1571737828, 'tile': "{'Action1': [200, 250, 300], 'Action2': [150, 200, 400]}", 'update_time': 1571737828}, '22': {'states': 's124', 'last_update_time': 1571737828, 'tile': "{'Action1': [100, 150, 400], 'Action2': [350, 500, 700]}", 'update_time': 1571737828}, '消息': '交通' }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-10
    • 2020-09-06
    • 2019-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-05
    相关资源
    最近更新 更多