Turn raw data into clear, Excel-like summary tables using GroupBy and pivot_table()
If you've started using groupby(), you're already doing powerful aggregations. But sometimes you need your summary to look like a proper table — with rows, columns, and values in the right places — just like pivot tables in Excel.
That's exactly what df.pivot_table() does. It uses GroupBy under the hood but automatically reshapes the result into a clean, readable table.
Our Sample DataFrame
Let's use sales data from a small company:
Region
Product
Year
Sales
0
North
Laptop
2023
1200
1
North
Phone
2023
800
2
South
Laptop
2023
1100
3
South
Phone
2023
900
4
East
Laptop
2024
1300
5
East
Phone
2024
850
6
West
Laptop
2024
1400
7
West
Phone
2024
950
8
North
Phone
2024
820
9
South
Laptop
2024
1150
Simple GroupBy Recap
First, a quick GroupBy example (total sales by Region):
df.groupby('Region')['Sales'].sum()
Output (Series):
| Region | Sales |
|---|---|
| East | 2150 |
| North | 2820 |
| South | 3150 |
| West | 2350 |
Enter pivot_table() – GroupBy Made Beautiful
Use pivot_table() when you want:
- Rows = one category (e.g., Region)
- Columns = another category (e.g., Product)
- Values = aggregated numbers (e.g., total Sales)
Region
Laptop
Phone
East
1300
850
North
1200
1620
South
2250
900
West
1400
950
Add Totals and Multiple Aggregations
Region
Laptop
Phone
Total
East
1300
850
2150
North
1200
1620
2820
South
2250
900
3150
West
1400
950
2350
Total
6150
4320
10470
Key Parameters of pivot_table()
values— column to aggregateindex— rows (can be list for multi-level)columns— columns (can be list)aggfunc— 'sum', 'mean', 'count', etc. (or list for multiple)margins=True— add row/column totalsfill_value=0— replace NaN with 0
When to Use Which?
- Use plain
groupby()for quick summaries or when you don't need reshaping. - Use
pivot_table()for reports, dashboards, or when you want an Excel-style cross-tab view.
Happy Learning, Ritesh! 🐼
Comments
Post a Comment