简体   繁体   中英

Converting python dataframe to json format

Im trying to convert a python dictionary to json.
Input dataframe looks like this:

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]}

Already tried this, but it does not provide the required output format as shown below in the expected json output format

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

Expected json output file:

{
  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"
}

A solution for this output would really help me.

I would try:

# 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')

The output is the desired.

The following line should give you the result you expect, assuming that the id_user is your dataframe's index:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM