Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • 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:
Pandas Groupby: Summarising, Aggregating, and Grouping data in Python
Next article icon

Pandas Groupby: Summarising, Aggregating, and Grouping data in Python

Last Updated : 29 Aug, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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 trying things over and over, so for efficiency, we use Groupby concept. Groupby concept is really important because of its ability to summarize, aggregate, and group data efficiently.

Summarize

Summarization includes counting, describing all the data present in data frame. We can summarize the data present in the data frame using describe() method. This method is used to get min, max, sum, count values from the data frame along with data types of that particular column.

  • describe(): This method elaborates the type of data and its attributes.

Syntax:

dataframe_name.describe()

  • unique(): This method is used to get all unique values from the given column.

Syntax:

dataframe['column_name].unique()

  • nunique(): This method is similar to unique but it will return the count the unique values.

Syntax:

dataframe_name['column_name].nunique()

  • info(): This command is used to get the data types and columns information

Syntax:

dataframe.info()

  • columns: This command is used to display all the column names present in data frame

Syntax:

dataframe.columns

Example:

We are going to analyze the student marks data in this example.

Python3
# importing pandas as pd for using data frame import pandas as pd  # creating dataframe with student details dataframe = pd.DataFrame({'id': [7058, 4511, 7014, 7033],                           'name': ['sravan', 'manoj', 'aditya', 'bhanu'],                           'Maths_marks': [99, 97, 88, 90],                           'Chemistry_marks': [89, 99, 99, 90],                           'telugu_marks': [99, 97, 88, 80],                           'hindi_marks': [99, 97, 56, 67],                           'social_marks': [79, 97, 78, 90], })  # display dataframe dataframe 

Output:

Python3
# describing the data frame print(dataframe.describe())  print("-----------------------------") # finding unique values print(dataframe['Maths_marks'].unique())  print("-----------------------------") # counting unique values print(dataframe['Maths_marks'].nunique())  print("-----------------------------") # display the columns in the data frame print(dataframe.columns)  print("-----------------------------") # information about dataframe print(dataframe.info()) 

Output:

Aggregation

Aggregation is used to get the mean, average, variance and standard deviation of all column in a dataframe or particular column in a data frame.

  • sum(): It returns the sum of the data frame

Syntax:

dataframe['column].sum()

  • mean(): It returns the mean of the particular column in a data frame

Syntax:

dataframe['column].mean()

  • std(): It returns the standard deviation of that column.

Syntax:

dataframe['column].std()

  • var(): It returns the variance of that column

dataframe['column'].var()

  • min(): It returns the minimum value in column

Syntax:

dataframe['column'].min()

  • max(): It returns maximum value in column

Syntax:

dataframe['column'].max()

Example:

In the below program we will aggregate data.

Python3
# importing pandas as pd for using data frame import pandas as pd  # creating dataframe with student details dataframe = pd.DataFrame({'id': [7058, 4511, 7014, 7033],                           'name': ['sravan', 'manoj', 'aditya', 'bhanu'],                           'Maths_marks': [99, 97, 88, 90],                           'Chemistry_marks': [89, 99, 99, 90],                           'telugu_marks': [99, 97, 88, 80],                           'hindi_marks': [99, 97, 56, 67],                           'social_marks': [79, 97, 78, 90], })  # display dataframe dataframe 

Output:

Python3
# getting all minimum values from  # all columns in a dataframe print(dataframe.min()) print("-----------------------------------------")  # minimum value from a particular  # column in a data frame print(dataframe['Maths_marks'].min()) print("-----------------------------------------")  # computing maximum values print(dataframe.max()) print("-----------------------------------------")  # computing sum print(dataframe.sum()) print("-----------------------------------------")  # finding count print(dataframe.count()) print("-----------------------------------------")   # computing standard deviation print(dataframe.std()) print("-----------------------------------------")  # computing variance print(dataframe.var()) 

Output:

Grouping

It is used to group one or more columns in a dataframe by using the groupby() method. Groupby mainly refers to a process involving one or more of the following steps they are:

  • Splitting: It is a process in which we split data into group by applying some conditions on datasets.
  • Applying: It is a process in which we apply a function to each group independently
  • Combining: It is a process in which we combine different datasets after applying groupby and results in a data structure

Example 1:

Python3
# importing pandas as pd for using data frame import pandas as pd  # creating dataframe with student details dataframe = pd.DataFrame({'id': [7058, 4511, 7014, 7033],                           'name': ['sravan', 'manoj', 'aditya', 'bhanu'],                           'Maths_marks': [99, 97, 88, 90],                           'Chemistry_marks': [89, 99, 99, 90],                           'telugu_marks': [99, 97, 88, 80],                           'hindi_marks': [99, 97, 56, 67],                           'social_marks': [79, 97, 78, 90], })   # group by name print(dataframe.groupby('name').first())  print("---------------------------------") # group by name with social_marks sum print(dataframe.groupby('name')['social_marks'].sum()) print("---------------------------------")  # group by name with maths_marks count print(dataframe.groupby('name')['Maths_marks'].count()) print("---------------------------------")  # group by name with maths_marks print(dataframe.groupby('name')['Maths_marks']) 

Output:

Example 2:

Python3
# importing pandas as pd for using data frame import pandas as pd  # creating dataframe with student details dataframe = pd.DataFrame({'id': [7058, 4511, 7014, 7033],                           'name': ['sravan', 'manoj', 'aditya', 'bhanu'],                           'Maths_marks': [99, 97, 88, 90],                           'Chemistry_marks': [89, 99, 99, 90],                           'telugu_marks': [99, 97, 88, 80],                           'hindi_marks': [99, 97, 56, 67],                           'social_marks': [79, 97, 78, 90], })  # group by name print(dataframe.groupby('name').first())  print("------------------------") # group by name with social_marks sum print(dataframe.groupby('name')['social_marks'].sum()) print("------------------------") # group by name with maths_marks count print(dataframe.groupby('name')['Maths_marks'].count()) 

Output:


Next Article
Pandas Groupby: Summarising, Aggregating, and Grouping data in Python

S

sravankumar_171fa07058
Improve
Article Tags :
  • Python
  • Python-pandas
  • Python pandas-groupby
Practice Tags :
  • python

Similar Reads

    Grouping and Aggregating with Pandas
    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
    3 min read
    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
    Grouping Categorical Variables in Pandas Dataframe
    Firstly, we have to understand what are Categorical variables in pandas. Categorical are the datatype available in pandas library of python. A categorical variable takes only a fixed category (usually fixed number) of values. Some examples of Categorical variables are gender, blood group, language e
    2 min read
    How to combine Groupby and Multiple Aggregate Functions in Pandas?
    Pandas is an open-source Python library built on top of NumPy. It allows data structures and functions to manipulate and analyze numerical data and time series efficiently. It is widely used in data analysis for tasks like data manipulation, cleaning and exploration. One of its key feature is to gro
    3 min read
    Pyspark GroupBy DataFrame with Aggregation or Count
    Pyspark is a powerful tool for handling large datasets in a distributed environment using Python. One common operation when working with data is grouping it based on one or more columns. This can be easily done in Pyspark using the groupBy() function, which helps to aggregate or count values in each
    2 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