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)