I would like to get a cross-table by using pandas dataframe with Python like this:
Home | Away | Tot | |
---|---|---|---|
played | 19 | 19 | 38 |
wins | 10 | 8 | 18 |
draws | 7 | 5 | 12 |
loss | 2 | 6 | 8 |
goals_for | 40 | 26 | 66 |
goals_against | 17 | 19 | 36 |
avg_goal_for | 2.1 | 1.4 | 1.7 |
avg_goal_against | 0.9 | 1.0 | 0.9 |
and the json file is :
{
"get": "teams/statistics",
"response": {
"fixtures": {
"played": {
"home": 19,
"away": 19,
"total": 38
},
"wins": {
"home": 10,
"away": 8,
"total": 18
},
"draws": {
"home": 7,
"away": 5,
"total": 12
},
"loses": {
"home": 2,
"away": 6,
"total": 8
}
},
"goals": {
"for": {
"total": {
"home": 40,
"away": 26,
"total": 66
},
"average": {
"home": "2.1",
"away": "1.4",
"total": "1.7"
}
},
"against": {
"total": {
"home": 17,
"away": 19,
"total": 36
},
"average": {
"home": "0.9",
"away": "1.0",
"total": "0.9"
}
}
}
}
}
I don’t know how to handle all nested dictionaries in an easy way.
Please someone can help me out.
Thanks
2
Answers
I think you first need to un-nest your dictionary, I recommend a recursive function to do so.
if you want to do something that works for any occasion you can do something such as
output
One way to do this is to process both halves of your
response
separately, usingjson_normalize
to read the data, then splitting the column names to a multi-level index and then usingstack
to move to a long format from the wide format. You can then drop the top-level index andconcat
the two dataframes:Output:
Note, if desired you can rename the index column to match your question using
Output: