Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Data Science
  3. Question
Data Science

How to perform a group by function in Python?

Asked by Ranjana Admin Jan 15, 2020 2.2K views 2 answers
Share

Your answer

2 Answers

Eternalwigs Latest answer

Answered on Mar 28, 2025

The groupby() function in Pandas is used to group rows based on a specific column and perform aggregate operations on them. Eternalwigs 


Steps to Perform groupby() in Pandas:

Create a DataFrame


python

Copy

Edit

import pandas as pd


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

        'Person': ['Sam', 'Charlie', 'Amy', 'Vanessa', 'Carl', 'Sarah'],

        'Sales': [200, 120, 340, 124, 243, 350]}


df = pd.DataFrame(data)

print(df)

This creates a DataFrame with three columns: Company, Person, and Sales.


Grouping by a Column

To group the data by Company, use:


python

Copy

Edit

df.groupby('Company')

This returns a DataFrameGroupBy object, which can be used for further operations.


Applying Aggregate Functions

We can apply aggregation methods like mean(), sum(), count(), etc.


python

Copy

Edit

by_comp = df.groupby("Company")

print(by_comp.mean()) # Calculates the average sales per company

This will return the mean Sales for each company.

Was this helpful?

More Data Science discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest Data Science Blogs

Guides, tips and career advice on Data Science from JanBask experts.