I would like to efficiently transform a dataframe df of the below structure
| country | sector | production |
|---|---|---|
| US | automotive | 100 |
| US | aviation | 50 |
| CA | automotive | 30 |
| CA | aviation | 15 |
| JP | automotive | 95 |
| JP | aviation | 25 |
using the mapping (avilable as dictionary mapping_dict)
| region | countries |
|---|---|
| region_1 | US, CA |
| region_2 | US, JP |
into the aggregated pivot-table of the form
| region_1 | region_2 | |
|---|---|---|
| automotive | 115 | 195 |
| aviation | 1200 | 1400 |
without using loops. Before using pivot, I tried to aggregate by using the dictionary and map, but this won't work due to countries belonging to multiple regions.
df['country'] = df['country'].map(mapping_dict)
MWE input data:
df = pd.DataFrame(
{
"country": ['US', 'US', 'CA', 'CA', 'JP', 'JP'],
"sector": ['automotive', 'aviation', 'automotive', 'aviation', 'automotive', 'aviation'],
"production": [100, 50, 30, 15, 95, 25]
}
)
dict_country_per_region = {'region_1': 'US, CA', 'region_2': 'US, JP'}