← Back to Pandas Course | Chapter 7: Grouping & Aggregation | Lesson 1 of 7

groupby() basics

groupby splits rows into groups by a column, so you can summarize each group separately.

In this page:

  1. groupby() basics
Syntax
python
df.groupby("column")
df.groupby("column")["value_column"].sum()

groupby() basics

df.groupby("col") creates a lazy grouping object. Applying an aggregation like sum, mean or count computes one result per group. It follows a split-apply-combine pattern. The group keys become the index of the result.

Note: Use as_index=False to keep the group column as a regular column.

Example: groupby() basics

python
import pandas as pd

df = pd.DataFrame({"dept": ["A", "B", "A", "B"], "salary": [100, 200, 150, 250]})
print(df.groupby("dept")["salary"].sum())
print(df.groupby("dept", as_index=False)["salary"].mean())

# Output:
# dept
# A    250
# B    450
# Name: salary, dtype: int64
#   dept  salary
# 0    A   125.0
# 1    B   225.0
Related Topics
Common Mistakes
  1. Forgetting to apply an aggregation
  2. Losing the key to the index unintentionally
  3. Grouping by a column with NaN, which is dropped by default
Chapter Summary
  • groupby splits data into groups
  • Aggregations run per group
  • Keys become the index
  • as_index=False keeps them as a column
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.