I'm trying to create a nested Json file from a pandas dataframe. I found a similar question here but when I tried to apply the answer, the output wasn't what I really wanted. I tried to adjust the code to get the desired answer but I haven't been able to.
Let me explain the problem first then I will sow you what I have done so far.
I have the following dataframe:
Region staff_id rate dep
1 300047 77 4
1 300048 45 3
1 300049 32 7
2 299933 63 8
2 299938 86 7
Now I want the json object to look like this:
{'region': 1 :
{ 'Info': [
{'ID': 300047, 'Rate': 77, 'Dept': 4},
{'ID': 300048, 'Rate': 45, 'Dept': 3},
{'ID': 300049, 'Rate': 32, 'Dept': 7}
]
},
'region': 2 :
{ 'Info': [
{'ID': 299933, 'Rate': 63, 'Dept': 8},
{'ID': 299938, 'Rate': 86, 'Dept': 7}
]
}
}
So for every region, there is a tag called info and inside info there is all the rows of that region.
I tried this code from the previous answer:
json_output = list(df.apply(lambda row: {"region": row["Region"],"Info": [{
"ID": row["staff_id"], "Rate": row["rate"], "Dept": row["dep"]}]
},
axis=1).values)
Which will give me every row in the dataframe and not grouped by the region.
Sorry because this seems repetitive, but I have been trying to change that answer to fit mine and I would really appreciate your help.