How to map column in a Pandas DataFrameGroupBy object

Viewed 179

I have 2 columns in a dataframe and I am combining them together to produce a groupby object as follows

df.groupby(["Region","Population"]).size()

I also have the following hashtable which I would like to map the column "Regions" to. In other words, every region in the current groupby object is a key in mapping and I would like to replace it with its value. For example, 1 should be replaced by "Asia"

mapping = {
    "1":"Asia", 
    "2":"Europe",
    "3":"North America", 
    "4":"South America",
    "5":"Oceania", 
    "6":"Africa",
    "7":"Antartica", 
}

How would I go about doing it? I know how to use the map function for a DataFrame but I need the final output to be a groupby object (Part of the requirements). I would also prefer not to directly map regions in my original dataframe (the variable names df) because it has ~2m data points which would be a lot more inefficient as compared to mapping the rows in the groupby object.

2 Answers

df_grouped.rename(index=mapping,inplace=True) should work.

You can map before groupby:

df.groupby([df["Region"].map(mapping),"Industry"]).size()
Related