Pandas — GroupBy
Basic groupby
import pandas as pd
df = pd.DataFrame({
'department': ['HR', 'HR', 'IT', 'IT', 'Sales', 'Sales'],
'salary': [50000, 55000, 60000, 65000, 70000, 75000]
})
# Group and aggregate
print(df.groupby('department')['salary'].mean())
Multiple aggregations
df.groupby('department')['salary'].agg(['mean', 'min', 'max', 'count'])
Custom aggregation
df.groupby('department')['salary'].agg(lambda x: x.max() - x.min())
Multiple columns
df.groupby(['department', 'level'])['salary'].mean()
Iteration
for name, group in df.groupby('department'):
print(name)
print(group)
Mini Practice
- Group by column
- Apply aggregations
- Use multiple aggregations
- Iterate over groups
Up Next
Continue with Merge - Combining DataFrames.
Related Topics
Frequently Asked Questions about GroupBy
What is GroupBy in Pandas?
GroupBy is a fundamental concept in Pandas. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn GroupBy?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn GroupBy.
Why is GroupBy important in Pandas?
GroupBy is essential for Pandas development. Understanding this concept will help you write better code and solve real-world problems more effectively.