I am struggling to find a recursive mapping to get the end result. Here is the input df
## mapping recursive
import pandas as pd
data = {
"group1": ["A", "A", "B", "B"],
"group2": ["grp1", "grp2", "grp1", "grp2"],
"hc": [50, 40, 45, 90],
"response": [12, 30, 43, 80]
}
#load data into a DataFrame object:
df = pd.DataFrame(data)
df
I would like to map recursively to convert the df
into a Python dictionary. Each number is in a details
list, and it is recursively mapped through the aggregated data frame. For example, level A total_hc
is the sum of hc of group1
is A
.
## desired output
output = {
"rows":[
{
"details": [{
"level": "A",
"total_hc": 90,
"response_total": 42
}],
"rows":[
{
"details": [{
"level": "grp1",
"total_hc": 50,
"response_total": 12
}]
},
{
"details": [{
"level": "grp2",
"total_hc": 40,
"response_total": 30
}],
}
]
},
{
"details": [{
"level": "B",
"total_hc": 135,
"response_total": 123
}],
"rows":[
{
"details": [{
"level": "grp1",
"total_hc": 45,
"response_total": 43
}]
},
{
"details": [{
"level": "grp2",
"total_hc": 90,
"response_total": 80
}],
}
]
}
]
}
I tried to group the df
## group by function
group_df = df.groupby(["group1", "group2"]).sum()
group_df.to_dict("index")
Then I am struggling to find a recursive mapping to get the end result. Appreciate anyone who can help out.