Year temp Name DateTime
1950 0 De Bilt 010100
1951 1 De Bilt 010100
1950 2 De Bilt 010101
1951 3 De Bilt 010101
1950 0 Arcen 010100
1951 1 Arcen 010100
I have this dataframe (df_stations) and would like to create a JSON out of it in the following format:
{
"De Bilt": {
"010100": {
"1950": {
"temp": 0
},
"1951": {
"temp": 1
}
},
"010101": {
"1950": {
"temp": 2
},
"1951": {
"temp": 3
}
}
},
"Arcen": {
"010100": {
"1950": {
"temp": 0
},
"1951": {
"temp": 1
}
},
...
However, the following code doesn't give me the right results:
def f(x):
return (dict({k:v for k,v in zip(x.DateTime,x.Year)},**{'temp':x.temp.iloc[0]}))
(
df_stations.groupby(['Name','DateTime','Year'])
.apply(f)
.groupby(level=0)
.apply(lambda x: x.tolist())
.to_dict()
)
Can someone help me with this? Thanks a lot!