Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. Master Data Science with Python

Lesson 26 of 60 · python

Pivot Tables and Crosstabulations

Duration: 20 minutes

Pivot Tables

pivot_table reshapes data, aggregating values across two dimensions.

Simple pivot

sales = pd.read_csv('sales.csv')
# Total revenue per store per month
pivot = sales.pivot_table(values='revenue', index='store_id', columns='month', aggfunc='sum', fill_value=0)
print(pivot)

Multiple aggregation functions

pivot_multi = sales.pivot_table(values='units', index='store_id', columns='product_category', aggfunc=['sum', 'mean'], fill_value=0)
print(pivot_multi)

Using crosstab

# Cross tab of gender vs. purchased product
tab = pd.crosstab(df['gender'], df['product'])
print(tab)

Adding margins (totals)

pivot = sales.pivot_table(values='revenue', index='store_id', columns='month', aggfunc='sum', margins=True)
print(pivot)

Info

pivot_table is more flexible than pivot because it can handle duplicate entries with an aggregation function.

Previous: Merging and Joining DataFramesNext: Time Series Data with Pandas