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
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Pivot Tables and Cro | Master Data Science with Python lesso | BraveProgrammer
  1. Courses
  2. /
  3. Master Data Science with Python

Lesson 26 of 60

·python

Pivot Tables and Crosstabulations

20 minutes

Course progress43%

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=)
(pivot)
0
print

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.
Make it stickPractice what you've learned1 quiz · 4 practical tests · Optional activities from Master Data Science with PythonBrowse activities
Previous lessonMerging and Joining DataFramesContinue to lesson 27Time Series Data with PandasBack to Master Data Science with Python curriculum