Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 14

Pandas GroupBy: Aggregation and Grouping

This lesson is built with resources from realpython.com and jakevdp.github.io.

Hello! Welcome back to our journey through Python's powerful data manipulation tools.

In the last lesson, you mastered how to select and filter data using boolean indexing, .loc, and .iloc. You learned how to isolate specific rows and columns, such as finding all employees in the 'IT' department. That was about selecting data. Now, we'll focus on what you can do with those selections.

This lesson addresses the learning outcome: Perform grouping and aggregation operations in Pandas. We'll move from asking "Which employees are in the IT department?" to "What is the average salary of the IT department compared to others?"

For you as a software engineer, this is the Pandas equivalent of SQL's GROUP BY clause combined with aggregate functions like AVG(), SUM(), and COUNT(). You'll discover it's a cornerstone of data analysis, allowing you to summarize vast datasets into meaningful insights.

We'll explore this through the powerful "Split-Apply-Combine" strategy, which is the fundamental concept behind grouping in Pandas.

The "Split-Apply-Combine" Paradigm

At its core, any group-based operation follows three steps:

  1. Split: The data is broken into groups based on some criteria (e.g., by department, by region).
  2. Apply: A function is applied independently to each of these smaller groups (e.g., calculate the mean, sum the values, or perform a more complex transformation).
  3. Combine: The results from all the groups are stitched back together into a single, summary DataFrame.

This mental model is crucial for understanding how groupby works.

Split-Apply-Combine Paradigm
This image from the Python Data Science Handbook visually breaks down the Split-Apply-Combine strategy. An input DataFrame is split by a 'key' column, a function (sum) is applied to each group's 'data', and the results are combined into a final output.

To get a solid conceptual foundation, let's start with a reading that introduces this paradigm.

Aggregation and Grouping | Python Data Science Handbook

The 'Python Data Science Handbook' provides a fantastic, clear explanation of the Split-Apply-Combine concept and the 'lazy' nature of the GroupBy object.

Please read the section titled 'GroupBy: Split, Apply, Combine'. Pay close attention to the three steps and the idea that df.groupby('key') returns a special DataFrameGroupBy object that hasn't performed any computation yet.

An important takeaway from this reading is that the groupby() operation is lazy. When you call df.groupby('department'), Pandas doesn't immediately start splitting your data. Instead, it returns a DataFrameGroupBy object that contains all the information needed to perform the split. The actual "apply" and "combine" steps only happen when you call an action on this object, like .sum() or .mean(). This lazy evaluation allows for highly efficient computations.


Basic Grouping and Aggregation

Let's continue with the employee DataFrame from our last lesson and put this into practice.

import pandas as pd

data = {
    'employee_id': [101, 102, 103, 104, 105, 106],
    'department': ['Sales', 'IT', 'IT', 'Marketing', 'Sales', 'IT'],
    'salary': [70000, 85000, 92000, 65000, 72000, 110000],
    'years_at_company': [3, 5, 6, 2, 4, 8]
}
df = pd.DataFrame(data)

1. Grouping by a Single Column

To calculate the average salary for each department, we first group by the department column and then select the salary column to apply the .mean() aggregation.

# The full split-apply-combine chain
avg_salary_by_dept = df.groupby('department')['salary'].mean()

print(avg_salary_by_dept)
# department
# IT           95666.666667
# Marketing    65000.000000
# Sales        71000.000000
# Name: salary, dtype: float64

Here, df.groupby('department') performs the split. Then, ['salary'].mean() performs the apply (calculating the mean of the salary for each group) and combine (assembling the results into a new Series).

2. Grouping by Multiple Columns

You can also group by multiple criteria. For example, let's find the number of employees for each combination of department and years at the company. A simple way to count rows is with .size().

# Group by two columns
employee_count = df.groupby(['department', 'years_at_company']).size()

print(employee_count)
# department  years_at_company
# IT          5                   1
#             6                   1
#             8                   1
# Marketing   2                   1
# Sales       3                   1
#             4                   1
# dtype: int64

Notice the output has a MultiIndex with both department and years_at_company as index levels.

The following reading provides more hands-on examples and introduces an analogy to SQL, which should resonate with your backend experience.

pandas GroupBy: Your Guide to Grouping Data in Python

The Real Python article 'pandas GroupBy: Your Guide to Grouping Data in Python' offers a great practical walkthrough of these initial steps.

Read the section 'The Hello, World! of pandas GroupBy'. It demonstrates grouping by single and multiple columns and compares it directly to a SQL query, which is a useful parallel.

Test your understanding!

Using the df DataFrame, find the highest salary within each department.

Show answer
# Find the maximum salary for each department
max_salary_by_dept = df.groupby('department')['salary'].max()
print(max_salary_by_dept)

# Expected output:
# department
# IT           110000
# Marketing     65000
# Sales         72000
# Name: salary, dtype: int64

Advanced Aggregation with .agg()

What if you need more than one summary statistic? For example, for each department, you want to know the average salary, the median salary, and the total number of employees. Chaining individual aggregations would be inefficient. This is where the .agg() method comes in.

The .agg() method is highly flexible and allows you to:

  1. Apply multiple functions at once to a single column.
  2. Apply different functions to different columns.

Let's explore these patterns, which are clearly explained in the Python Data Science Handbook.

Aggregation and Grouping | Python Data Science Handbook

Let's return to the 'Python Data Science Handbook' to see how .agg() enables more complex, customized aggregations.

Focus on the sub-section titled 'Aggregation'. It shows how to pass a list of functions to .aggregate() (an alias for .agg()) and how to use a dictionary to specify per-column aggregations.

Here are examples using our employee DataFrame:

1. Multiple aggregations on the same column:
Let's find the mean, median, and minimum salary for each department.

dept_salary_stats = df.groupby('department')['salary'].agg(['mean', 'median', 'min'])
print(dept_salary_stats)
#                    mean  median    min
# department
# IT          95666.666667   92000  85000
# Marketing   65000.000000   65000  65000
# Sales       71000.000000   71000  70000

2. Different aggregations on different columns:
Using a dictionary, we can find the mean salary and the maximum tenure (years_at_company) for each department.

dept_summary = df.groupby('department').agg({
    'salary': 'mean',
    'years_at_company': 'max'
})
print(dept_summary)
#                 salary  years_at_company
# department
# IT          95666.666667                 8
# Marketing   65000.000000                 2
# Sales       71000.000000                 4

Beyond Aggregation: Transform and Filter

The "apply" step is not limited to just aggregation. Two other powerful operations are transformation and filtering.

Transformation with .transform()

While aggregation reduces a group to a single value (like the mean), a transformation applies a function to a group and returns a result with the same shape as the original data.

A classic use case is group-wise normalization. For instance, how does each employee's salary compare to the average salary of their specific department?

# 1. Calculate the mean salary for each department
mean_salary_per_dept = df.groupby('department')['salary'].transform('mean')

# 2. This returns a Series with the same index as the original df
df['dept_avg_salary'] = mean_salary_per_dept
df['salary_vs_dept_avg'] = df['salary'] - df['dept_avg_salary']

print(df[['department', 'salary', 'salary_vs_dept_avg']])
#   department  salary  salary_vs_dept_avg
# 0      Sales   70000         -1000.000000
# 1         IT   85000        -10666.666667
# 2         IT   92000         -3666.666667
# 3  Marketing   65000             0.000000
# 4      Sales   72000          1000.000000
# 5         IT  110000         14333.333333

This is a powerful way to create features for machine learning models.

Filtering with .filter()

Sometimes you want to discard entire groups based on a condition. For example, maybe you only want to analyze departments with more than one employee. The .filter() method is designed for this. It takes a function that returns True or False for each group.

# Keep only departments with more than 1 employee
large_departments = df.groupby('department').filter(lambda group: len(group) > 1)

print(large_departments)
#    employee_id department  salary  years_at_company
# 0          101      Sales   70000                 3
# 1          102         IT   85000                 5
# 2          103         IT   92000                 6
# 4          105      Sales   72000                 4
# 5          106         IT  110000                 8

In this case, the 'Marketing' department, which has only one employee, is excluded from the result.

The Python Data Science Handbook subsections on "Transformation" and "Filtering" in resource_id: [LINK](https://jakevdp.github.io/PythonDataScienceHandbook/03.08-aggregation-and-grouping.html) provide concise examples of these two methods. I recommend reviewing them.


A Note on Performance

As a software engineer, you appreciate efficient code. When working with groupby, you might be tempted to use .apply() with a custom lambda function for complex operations. While flexible, .apply() can be slow because it often resorts to iterating over the groups in Python.

Whenever possible, prefer built-in, vectorized aggregations (.mean(), .sum(), .transform(), etc.). These are highly optimized in Cython and are significantly faster.

The Real Python article (resource_id: [LINK](https://realpython.com/pandas-groupby/)) has an excellent section titled "Improving the Performance of .groupby()" that demonstrates this performance difference. For large datasets, this knowledge is critical.


Conclusion

You've now learned how to leverage the powerful groupby functionality in Pandas to summarize and analyze your data effectively.

Key Takeaways:

  • Split-Apply-Combine is the fundamental paradigm for all grouping operations.
  • Use df.groupby() to initiate the split, which creates a lazy GroupBy object.
  • Use aggregation methods like .mean(), .max(), or the flexible .agg() to summarize groups.
  • Use .transform() to perform group-specific calculations while retaining the original data's shape.
  • Use .filter() to include or exclude entire groups based on a condition.
  • For performance, prioritize built-in, vectorized groupby methods over custom .apply() functions whenever possible.

Next up:
We can now calculate powerful summary statistics, like the average salary per department. But numbers in a table only tell part of the story. In our next and final lesson of this module, we will learn how to visualize these summaries using Matplotlib and Seaborn, turning our aggregated data into insightful charts and plots that are much easier to interpret.