1

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.

0

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

You can map before groupby:

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

2 Comments

That works. Thanks! Do you happen to know how to increase the width of a column for the groupby object or truncate values that are too long?
I'm not entirely sure. You can checkout display options.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.