How to perform a group by function in Python?

814    Asked by ranjan_6399 in Data Science , Asked on Jan 15, 2020
Answered by Ranjana Admin

To perform a groupby function, we need to create a dataframe.Let us create a dataframe.

import pandas as pd

# Create dataframe

data = {'Company':['GOOG','GOOG','MSFT','MSFT','FB','FB'],



df = pd.DataFrame(data)


The dataframe looks like below

Now we can use the .groupby() method to group rows together based off of a column name. For instance let's group based off of Company. This will create a DataFrameGroupBy object


We can save this object as a new variable:

by_comp = df.groupby("Company")

And then call aggregate methods off the object:


Your Answer


Parent Categories