The groupby() function is one of the most powerful features in Pandas. It allows you to split data into groups, apply calculations such as sum, mean, count, min, and max, and combine the results into meaningful summaries. GroupBy is widely used in sales reporting, HR analytics, financial analysis, inventory management, and business intelligence dashboards. In this chapter, you’ll practice solving real-world GroupBy problems using Pandas. Pandas GroupBy practice questions with solutions help to understand the concepts.
1. Python Program to Calculate Total Sales by Department
Problem Statement
Write a Python program to calculate the total sales for each department using groupby().
Python Solution
import pandas as pd
data = {
"Department": ["IT", "HR", "IT", "HR", "Finance"],
"Sales": [5000, 6000, 4500, 5500, 7000]
}
df = pd.DataFrame(data)
result = df.groupby("Department")["Sales"].sum()
print(result)
Sample Output
Department
Finance 7000
HR 11500
IT 9500
Name: Sales, dtype: int64
Explanation
The groupby() function groups rows by Department, and the sum() function calculates the total sales for each department.
Concepts Covered
groupby()sum()- Data Aggregation
2. Python Program to Calculate Average Salary by Department
Problem Statement
Write a Python program to calculate the average salary of employees in each department.
Python Solution
import pandas as pd
data = {
"Department": ["IT", "HR", "IT", "HR"],
"Salary": [50000, 45000, 55000, 47000]
}
df = pd.DataFrame(data)
result = df.groupby("Department")["Salary"].mean()
print(result)
Sample Output
Department
HR 46000.0
IT 52500.0
Name: Salary, dtype: float64
Explanation
The mean() function calculates the average salary for each department.
Concepts Covered
groupby()mean()- Average Calculation
3. Python Program to Count Employees in Each Department
Problem Statement
Write a Python program to count the number of employees in each department.
Python Solution
import pandas as pd
data = {
"Department": ["IT", "HR", "IT", "Finance", "HR", "IT"],
"Employee": ["Rahul", "Aman", "Priya", "Rohit", "Sneha", "Karan"]
}
df = pd.DataFrame(data)
result = df.groupby("Department")["Employee"].count()
print(result)
Sample Output
Department
Finance 1
HR 2
IT 3
Name: Employee, dtype: int64
Explanation
The count() function counts the number of employees in each department.
Concepts Covered
groupby()count()- Record Counting
4. Python Program to Find the Maximum Sales by Department
Problem Statement
Write a Python program to find the highest sales value in each department.
Python Solution
import pandas as pd
data = {
"Department": ["IT", "HR", "IT", "HR"],
"Sales": [5000, 6000, 4500, 5500]
}
df = pd.DataFrame(data)
result = df.groupby("Department")["Sales"].max()
print(result)
Sample Output
Department
HR 6000
IT 5000
Name: Sales, dtype: int64
Explanation
The max() function returns the highest sales value for each department.
Concepts Covered
groupby()max()- Maximum Value
5. Python Program to Find the Minimum Sales by Department
Problem Statement
Write a Python program to find the lowest sales value in each department.
Python Solution
import pandas as pd
data = {
"Department": ["IT", "HR", "IT", "HR"],
"Sales": [5000, 6000, 4500, 5500]
}
df = pd.DataFrame(data)
result = df.groupby("Department")["Sales"].min()
print(result)
Sample Output
Department
HR 5500
IT 4500
Name: Sales, dtype: int64
Explanation
The min() function returns the smallest sales value in each department.
Concepts Covered
groupby()min()- Minimum Value
6. Python Program to Calculate Multiple Aggregations Using GroupBy
Problem Statement
Write a Python program to calculate the sum, average, and maximum sales for each department.
Python Solution
import pandas as pd
data = {
"Department": ["IT", "HR", "IT", "HR", "Finance"],
"Sales": [5000, 6000, 4500, 5500, 7000]
}
df = pd.DataFrame(data)
result = df.groupby("Department")["Sales"].agg(
["sum", "mean", "max"]
)
print(result)
Sample Output
sum mean max
Department
Finance 7000 7000.0 7000
HR 11500 5750.0 6000
IT 9500 4750.0 5000
Explanation
The agg() function performs multiple aggregation operations in a single GroupBy statement.
Concepts Covered
groupby()agg()- Multiple Aggregations
7. Python Program to Group Data by Multiple Columns
Problem Statement
Write a Python program to calculate total sales by Department and Year.
Python Solution
import pandas as pd
data = {
"Department": [
"IT",
"IT",
"HR",
"HR",
"IT"
],
"Year": [
2024,
2025,
2024,
2025,
2024
],
"Sales": [5000, 6000, 4500, 5500, 3000]
}
df = pd.DataFrame(data)
result = df.groupby(
["Department", "Year"]
)["Sales"].sum()
print(result)
Sample Output
Department Year
HR 2024 4500
2025 5500
IT 2024 8000
2025 6000
Name: Sales, dtype: int64
Explanation
Passing multiple columns to groupby() creates grouped summaries based on multiple categories.
Concepts Covered
groupby()- Multiple Columns
- Hierarchical Grouping
8. Python Program to Group Data and Calculate Average Marks
Problem Statement
Write a Python program to calculate the average marks for students in each class.
Python Solution
import pandas as pd
data = {
"Class": ["A", "A", "B", "B"],
"Marks": [85, 90, 78, 88]
}
df = pd.DataFrame(data)
result = df.groupby("Class")["Marks"].mean()
print(result)
Sample Output
Class
A 87.5
B 83.0
Name: Marks, dtype: float64
Explanation
The mean() function calculates the average marks for each class.
Concepts Covered
groupby()- Average Calculation
- Data Analysis
9. Python Program to Group Data and Count Records
Problem Statement
Write a Python program to count the number of sales records for each department.
Python Solution
import pandas as pd
data = {
"Department": [
"IT",
"IT",
"HR",
"Finance",
"HR"
],
"Sales": [5000, 4500, 6000, 7000, 5500]
}
df = pd.DataFrame(data)
result = df.groupby("Department").size()
print(result)
Sample Output
Department
Finance 1
HR 2
IT 2
dtype: int64
Explanation
The size() function returns the number of rows in each group.
Concepts Covered
groupby()size()- Group Count
10. Python Program to Display First Record from Each Group
Problem Statement
Write a Python program to display the first record from each department.
Python Solution
import pandas as pd
data = {
"Department": [
"IT",
"IT",
"HR",
"HR"
],
"Employee": [
"Rahul",
"Priya",
"Aman",
"Sneha"
]
}
df = pd.DataFrame(data)
result = df.groupby("Department").first()
print(result)
Sample Output
Employee
Department
HR Aman
IT Rahul
Explanation
The first() function returns the first row from each group.
Concepts Covered
groupby()first()- Group Operations
11. Python Program to Display the Last Record from Each Group
Problem Statement
Write a Python program to display the last employee from each department using groupby().
Python Solution
import pandas as pd
data = {
"Department": ["IT", "IT", "HR", "HR", "Finance"],
"Employee": ["Rahul", "Priya", "Aman", "Sneha", "Rohit"]
}
df = pd.DataFrame(data)
result = df.groupby("Department").last()
print(result)
Sample Output
Employee
Department
Finance Rohit
HR Sneha
IT Priya
Explanation
The last() function returns the last row from each group.
Concepts Covered
groupby()last()- Group Operations
12. Python Program to Retrieve a Specific Group
Problem Statement
Write a Python program to retrieve all records belonging to the IT department.
Python Solution
import pandas as pd
data = {
"Department": ["IT", "HR", "IT", "Finance"],
"Employee": ["Rahul", "Aman", "Priya", "Rohit"],
"Salary": [50000, 45000, 55000, 70000]
}
df = pd.DataFrame(data)
group = df.groupby("Department")
print(group.get_group("IT"))
Sample Output
Department Employee Salary
0 IT Rahul 50000
2 IT Priya 55000
Explanation
The get_group() method retrieves all rows belonging to a specific group.
Concepts Covered
groupby()get_group()- Group Selection
13. Python Program to Group Data and Calculate Multiple Statistics
Problem Statement
Write a Python program to calculate the minimum, maximum, average, and total salary for each department.
Python Solution
import pandas as pd
data = {
"Department": ["IT", "HR", "IT", "HR", "Finance"],
"Salary": [50000, 45000, 55000, 47000, 70000]
}
df = pd.DataFrame(data)
result = df.groupby("Department")["Salary"].agg(
["min", "max", "mean", "sum"]
)
print(result)
Sample Output
min max mean sum
Department
Finance 70000 70000 70000.0 70000
HR 45000 47000 46000.0 92000
IT 50000 55000 52500.0 105000
Explanation
The agg() function can calculate multiple statistics simultaneously, making data analysis more efficient.
Concepts Covered
groupby()agg()- Multiple Statistics
14. Python Program to Group Data and Sort the Result
Problem Statement
Write a Python program to calculate total sales for each department and display the result in descending order.
Python Solution
import pandas as pd
data = {
"Department": ["IT", "HR", "Finance", "IT", "HR"],
"Sales": [5000, 6000, 7000, 4500, 5500]
}
df = pd.DataFrame(data)
result = df.groupby("Department")["Sales"].sum().sort_values(
ascending=False
)
print(result)
Sample Output
Department
HR 11500
IT 9500
Finance 7000
Name: Sales, dtype: int64
Explanation
The sort_values() function sorts the grouped results in descending order.
Concepts Covered
groupby()sort_values()- Data Sorting
15. Python Program to Group Data and Calculate Multiple Column Aggregations
Problem Statement
Write a Python program to calculate the total sales and average profit for each department.
Python Solution
import pandas as pd
data = {
"Department": ["IT", "HR", "IT", "HR"],
"Sales": [5000, 6000, 4500, 5500],
"Profit": [1000, 1200, 900, 1100]
}
df = pd.DataFrame(data)
result = df.groupby("Department").agg({
"Sales": "sum",
"Profit": "mean"
})
print(result)
Sample Output
Sales Profit
Department
HR 11500 1150.0
IT 9500 950.0
Explanation
Passing a dictionary to agg() allows you to apply different aggregation functions to different columns.
Concepts Covered
groupby()agg()- Multiple Column Aggregation
Chapter Summary
In this chapter, you learned how to use the groupby() function to organize, summarize, and analyze data efficiently. You practiced calculating totals, averages, minimums, maximums, counts, and multiple aggregations. You also learned how to group data using multiple columns, retrieve specific groups, sort grouped results, and apply different aggregation functions to multiple columns. These techniques are widely used in reporting, business intelligence, financial analysis, HR analytics, and data science.
Key Takeaways
groupby()groups data based on one or more columns.sum(),mean(),count(),min(), andmax()are common aggregation functions.agg()performs multiple aggregations in a single operation.- Multiple columns can be used for hierarchical grouping.
size()counts the number of rows in each group.first()andlast()return the first and last records of each group.get_group()retrieves a specific group.sort_values()sorts grouped results.- Different aggregation functions can be applied to different columns using a dictionary.
- GroupBy is one of the most frequently used techniques in real-world data analysis.
Frequently Asked Questions (FAQs)
1. What is the purpose of groupby() in Pandas?
The groupby() function groups rows based on one or more columns so that aggregation operations can be performed on each group.
2. Which aggregation functions are commonly used with groupby()?
Common aggregation functions include:
sum()mean()count()min()max()
3. How do you group data using multiple columns?
df.groupby(["Department", "Year"])
4. How do you calculate multiple statistics at once?
df.groupby("Department")["Sales"].agg(["sum", "mean", "max"])
5. How do you retrieve a specific group?
group = df.groupby("Department")
group.get_group("IT")
6. What is the difference between count() and size()?
count()counts only non-missing values.size()counts all rows, including those containing missing values.
7. Can groupby() be used with multiple aggregation functions for different columns?
Yes.
df.groupby("Department").agg({
"Sales": "sum",
"Profit": "mean"
})
8. Why is groupby() important in Pandas?
groupby() simplifies data summarization and reporting. It is widely used in business intelligence, finance, HR analytics, sales reporting, customer analysis, and machine learning data preprocessing.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
