In Python, especially in data science, the GroupBy operation in the Pandas library is one of the most powerful tools for data summarization and analysis. It allows you to split, apply, and combine data efficiently. Aggregation refers to computing summary statistics such as sum, mean, count, min, max, etc., on groups of data.
The GroupBy operation involves three steps:
Split → Divide the dataset into groups based on one or more keys.
Apply → Perform a function (like mean, sum, count) on each group.
Combine → Merge the results back into a single output.
This is useful for analyzing large datasets category-wise.
You can group by multiple columns:
Common aggregation functions:
sum() → Total of values
mean() → Average of values
count() → Number of entries
min() / max() → Minimum or maximum values
median() → Median
std() → Standard deviation
This calculates average salary per department.
This applies different aggregations on different columns.
This returns highest-paid employee from each department.
transform() returns the result with the same shape as the original dataset.
This adds a new column showing each employee's department-wise average salary.
You can filter out groups based on a condition:
This keeps only departments with more than 5 employees.
Consider a dataset:
| Name | Department | Salary |
|---|---|---|
| A | HR | 40000 |
| B | IT | 60000 |
| C | HR | 50000 |
Grouping by department:
Output:
| Department | Salary |
|---|---|
| HR | 90000 |
| IT | 60000 |
The GroupBy and Aggregation operations in Python are essential for any type of data analysis. They help in summarizing large datasets, computing category-wise statistics, filtering meaningful groups, and preparing data for further analysis or machine learning. These operations provide fast, flexible, and powerful ways to understand the structure and distribution of data.
Take quizzes related to this topic and see where you stand!
Start Quiz Now