I am new to python and pandas have a csv file with
.----.---------.-------.-------------------.-------------------.-------------------.-------------------.
| id | country | state | cold_stress_score | cold_stress_level | heat_stress_score | heat_stress_level |
:----+---------+-------+-------------------+-------------------+-------------------+-------------------:
| 1 | USA | NJ | 0.003 | low | 0.673 | moderate |
:----+---------+-------+-------------------+-------------------+-------------------+-------------------:
| 2 | USA | NJ | 0.001 | high | 0.2 | high |
:----+---------+-------+-------------------+-------------------+-------------------+-------------------:
| 3 | USA | NJ | 0.004 | moderate | 0.3 | low |
:----+---------+-------+-------------------+-------------------+-------------------+-------------------:
| 4 | USA | NY | 0.005 | moderate | 0.4 | moderate |
:----+---------+-------+-------------------+-------------------+-------------------+-------------------:
| 5 | USA | NY | 0.006 | high | 0.5 | high |
:----+---------+-------+-------------------+-------------------+-------------------+-------------------:
| 6 | USA | NY | 0.009 | low | 0.6 | low |
'----'---------'-------'-------------------'-------------------'-------------------'-------------------'
and i wanted to convert this into nested way of json
expected json
{
"id":1,
"country": "USA",
"state": "NJ",
"cold_stress":{
"cold_stress_score" : 0.003,
"cold_stress_level": "low",
},
"heat_stress":{
"heat_stress_score" : 0.0673,
"heat_stress_level": "moderate",
}
}
I tried this solution Convert Pandas Dataframe to nested JSON
j = (df.groupby(['id','country','state'], as_index=False)
.apply(lambda x: x[['cold_stress_score','cold_stress_level']].to_dict('r'))
.reset_index()
.rename(columns={0:'cold_stress'})
.to_json(orient='records'))
I wanted to add heat Stress to json the above code returning
"id":1,
"country": "USA",
"state": "NJ",
"cold_stress":{
"cold_stress_score" : 0.003,
"cold_stress_level": "low",
}
}
how can I able to add heat_stress my csv is too big and am looking for dynamic value populating in above like cold stress