Categories
Python Answers

How to use GroupBy with a Python Pandas DataFrame and select most common value?

Spread the love

To use GroupBy with a Python Pandas DataFrame and select most common value, we can use the pd.Series.mode aggregation.

For instance, we write

source.groupby(['Country','City'])['Short name'].agg(pd.Series.mode)

to call groupby on the source data frame.

And then we get the mode of the 'Short name' column values by calling agg with pd.Series.Mode.

We can convert thge returned result into a dataframe with the to_frame method.

For instance, we can write

source.groupby(['Country','City'])['Short name'].agg(pd.Series.mode).to_frame()

to call to_frame on the result to convert it to a data frame.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *