Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Data preprocessing
  • Data Manipulation
  • Data Analysis using Pandas
  • EDA
  • Pandas Exercise
  • Pandas AI
  • Numpy
  • Matplotlib
  • Plotly
  • Data Analysis
  • Machine Learning
  • Data science
Open In App
Next Article:
MongoDB Aggregation $group Command
Next article icon

Grouping and Aggregating with Pandas

Last Updated : 12 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

When working with large datasets it’s used to group and summarize the data to make analysis easier. Pandas a popular Python library provides powerful tools for this. In this article you’ll learn how to use Pandas’ groupby() and aggregation functions step by step with clear explanations and practical examples. 

Aggregation in Pandas

Aggregation means applying a mathematical function to summarize data. It can be used to get a summary of columns in our dataset like getting sum, minimum, maximum etc. from a particular column of our dataset. The function used for aggregation is agg() the parameter is the function we want to perform. Some functions used in the aggregation are:

  • sum()         : Compute sum of column values
  • min()          : Compute min of column values
  • max()         : Compute max of column values
  • mean()       : Compute mean of column
  • size()          : Compute column sizes
  • describe()  : Generates descriptive statistics
  • first()          : Compute first of group values
  • last()          : Compute last of group values
  • count()       : Compute count of column values
  • std()           : Standard deviation of column
  • var()           : Compute variance of column
  • sem()         : Standard error of the mean of column

Creating a Sample Dataset

Let’s create a small dataset of student marks in Maths, English, Science and History.

Python
import pandas as pd  df = pd.DataFrame([[9, 4, 8, 9],                    [8, 10, 7, 6],                    [7, 6, 8, 5]],                   columns=['Maths',  'English',                             'Science', 'History'])  print(df) 

Output:

Now that we have a dataset let’s perform aggregation.

1. Summing Up All Values (sum())

The sum() function adds up all values in each column.

Python
df.sum() 

Output:

2. Getting a Summary (describe())

Instead of calculating sum, mean, min and max separately we can use describe() which provides all important statistics in one go.

Python
df.describe() 

Output:

3. Applying Multiple Aggregations at Once (agg())

The .agg() function lets you apply multiple aggregation functions at the same time.

Python
df.agg(['sum', 'min', 'max']) 

Output:

Grouping in Pandas

Grouping in Pandas means organizing your data into groups based on some columns. Once grouped you can perform actions like finding the total, average, count or even pick the first row from each group. This method follows a split-apply-combine process:

  • Split the data into groups
  • Apply some calculation like sum, average etc.
  • Combine the results into a new table.

Let’s understand grouping in Pandas using a small bakery order dataset as an example.

Python
import pandas as pd  data = {     'Item': ['Cake', 'Cake', 'Bread', 'Pastry', 'Cake'],     'Flavor': ['Chocolate', 'Vanilla', 'Whole Wheat', 'Strawberry', 'Chocolate'],     'Price': [250, 220, 80, 120, 250] }  df = pd.DataFrame(data) print(df) 

Output:

Screenshot-2025-05-07-164107

Bakery dataset

Grouping Data by One Column Using groupby()

Let’s say we want to group the orders based on the Item column.

Python
grouped = df.groupby('Item') print(grouped) 

Output:

<pandas.core.groupby.generic.DataFrameGroupBy object at 0x7867484be150>

This doesn’t show the result directly it just creates a grouped object. To actually see the data we need to apply a method like .sum(), .mean() or first(). Let’s find the total price of each item sold:

Python
print(df.groupby('Item')['Price'].sum()) 

Output:

grouping-using-group-by

Grouping data by one columns

The above output shows the total earnings from each item.

Grouping by Multiple Columns

Now let’s group by Item and Flavor to see how each flavored item sold.

Python
print(df.groupby(['Item', 'Flavor'])['Price'].sum()) 

Output:

Grouping-by-multiple-columns

Grouping by multiple columns

The above output show Chocolate Cakes earned ₹500 and Vanilla Cake earned ₹220 and more.



Next Article
MongoDB Aggregation $group Command
author
devangj9689
Improve
Article Tags :
  • Python
  • Python-pandas
Practice Tags :
  • python

Similar Reads

  • Groupby without aggregation in Pandas
    Pandas is a great python package for manipulating data and some of the tools which we learn as a beginner are an aggregation and group by functions of pandas.  Groupby() is a function used to split the data in dataframe into groups based on a given condition. Aggregation on other hand operates on se
    4 min read
  • Pandas Groupby: Summarising, Aggregating, and Grouping data in Python
    GroupBy is a pretty simple concept. We can create a grouping of categories and apply a function to the categories. It’s a simple concept, but it’s an extremely valuable technique that’s widely used in data science. In real data science projects, you’ll be dealing with large amounts of data and tryin
    5 min read
  • MongoDB Aggregation $group Command
    The $group command in MongoDB's aggregation framework is a powerful tool for performing complex data analysis and summarization. It allows users to group documents based on specified keys and apply aggregate functions such as sum, count, average, min, max, and more. In this article, we will explore
    6 min read
  • Write custom aggregation function in Pandas
    Pandas in python in widely used for Data Analysis purpose and it consists of some fine data structures like Dataframe and Series. There are several functions in pandas that proves to be a great help for a programmer one of them is an aggregate function. This function returns a single value from mult
    4 min read
  • Python MongoDB - $group (aggregation)
    MongoDB is an open-source document-oriented database. MongoDB stores data in the form of key-value pairs and is a NoSQL database program. The term NoSQL means non-relational. In this article, we will see the use of $group in MongoDB using Python. $group operation In PyMongo, the Aggregate Method is
    3 min read
  • Count distinct in Pandas aggregation
    In this article, let's see how we can count distinct in pandas aggregation. So to count the distinct in pandas aggregation we are going to use groupby() and agg() method.   groupby(): This method is used to split the data into groups based on some criteria. Pandas objects can be split on any of thei
    2 min read
  • Pyspark GroupBy DataFrame with Aggregation or Count
    Pyspark is a powerful tool for working with large datasets in a distributed environment using Python. One of the most common tasks in data manipulation is grouping data by one or more columns. This can be accomplished using the groupBy() function in Pyspark, which allows you to group a DataFrame bas
    3 min read
  • Python | Pandas dataframe.aggregate()
    Dataframe.aggregate() function is used to apply some aggregation across one or more columns. Aggregate using callable, string, dict or list of string/callables. The most frequently used aggregations are: sum: Return the sum of the values for the requested axismin: Return the minimum of the values fo
    2 min read
  • Pandas Groupby and Sum
    It's a simple concept but it's an extremely valuable technique that's widely used in data science. It is helpful in the sense that we can : Compute summary statistics for every groupPerform group-specific transformationsDo the filtration of data The dataframe.groupby() involves a combination of spli
    2 min read
  • Pandas Groupby Average
    GroupBy operations are powerful tools for summarizing and aggregating data. One common operation is calculating the average (mean) of groups within a DataFrame. Whether you're analyzing sales data by region, customer behavior by age group, or any other grouped data, groupby() method combined with ag
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences