Editor

Create a Cross-Tabulation

Advanced · Write the code · from Pandas Pivot Tables and Cross-Tabulation for Business Analysis

From the lesson: Pandas Pivot Tables and Cross-Tabulation for Business Analysis

If you have ever used a pivot table in Excel or Google Sheets, you already understand the core idea. You take a flat table of raw data and reshape it into a summary that shows one variable along the rows, another along the columns, and computed values (sums, averages, counts) in the cells.

Read the lesson

Use pd.crosstab() to create a frequency table showing how many students from each grade_level chose each elective. Print the result.

import pandas as pd
df = pd.DataFrame({
'student': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'],
'grade_level': ['9th', '9th', '10th', '10th', '9th', '10th', '9th', '10th'],
'elective': ['Art', 'Music', 'Art', 'Art', 'Music', 'Music', 'Art', 'Art']
})
# Create a cross-tabulation of grade_level vs elective

More Pandas Pivot Table exercises

All Python exercises · 50 practice problems · Data Science & Machine Learning quiz