Python for Excel users · Lesson 9 of 14
Pivot tables in Python with pandas
Build Excel-style pivot tables with pandas pivot_table: rows, columns, values, sum or count, grand totals, filters and saving to Excel.
An Excel pivot table has four boxes: Rows, Columns, Values and Filters. pd.pivot_table has an argument for each of them: index for rows, columns, values and aggfunc (Sum, Count, Average…). Excel starts number fields on Sum, but pandas uses the mean if you leave aggfunc out, so always write it. Filters are a normal filter before the pivot.
import pandas as pd
df = pd.DataFrame({
"Month": ["Jan", "Jan", "Jan", "Feb", "Feb", "Feb", "Feb"],
"Region": ["North", "South", "North", "South", "North", "East", "East"],
"Sales": [120, 340, 410, 95, 150, 80, 60],
})
pt = pd.pivot_table(df, index="Region", columns="Month",
values="Sales", aggfunc="sum")
print(pt)Month Feb Jan Region East 140.0 NaN North 150.0 530.0 South 95.0 340.0
East had no sales in January, so that cell is NaN; Excel would leave it blank. The months are sorted A to Z: Feb before Jan.
Empty cells and grand totals
fill_value=0 writes 0 in empty cells. margins=True adds Excel's Grand Total row and column; margins_name sets its label.
import pandas as pd
df = pd.DataFrame({
"Month": ["Jan", "Jan", "Jan", "Feb", "Feb", "Feb", "Feb"],
"Region": ["North", "South", "North", "South", "North", "East", "East"],
"Sales": [120, 340, 410, 95, 150, 80, 60],
})
pt = pd.pivot_table(df, index="Region", columns="Month",
values="Sales", aggfunc="sum", fill_value=0,
margins=True, margins_name="Total")
print(pt)Month Feb Jan Total Region East 140 0 140 North 150 530 680 South 95 340 435 Total 385 870 1255
Put the columns in your order
Pick the columns in the order you want with a list, the way you would drag them in the field list. Sort the rows by any column with sort_values.
import pandas as pd
df = pd.DataFrame({
"Month": ["Jan", "Jan", "Jan", "Feb", "Feb", "Feb", "Feb"],
"Region": ["North", "South", "North", "South", "North", "East", "East"],
"Sales": [120, 340, 410, 95, 150, 80, 60],
})
pt = pd.pivot_table(df, index="Region", columns="Month",
values="Sales", aggfunc="sum", fill_value=0)
pt = pt[["Jan", "Feb"]]
pt["Total"] = pt.sum(axis=1)
print(pt.sort_values("Total", ascending=False))Month Jan Feb Total Region North 530 150 680 South 340 95 435 East 0 140 140
Count, Average and other summaries
Change aggfunc like "Summarize values by": "count", "mean", "max", "min". A list gives several at once. Without columns, you get a simple one-level summary.
import pandas as pd
df = pd.DataFrame({
"Month": ["Jan", "Jan", "Jan", "Feb", "Feb", "Feb", "Feb"],
"Region": ["North", "South", "North", "South", "North", "East", "East"],
"Sales": [120, 340, 410, 95, 150, 80, 60],
})
pt = pd.pivot_table(df, index="Region", values="Sales",
aggfunc=["sum", "count", "mean"])
print(pt.round(1)) sum count mean
Sales Sales Sales
Region
East 140 2 70.0
North 680 3 226.7
South 435 2 217.5To count rows with no numbers involved, pd.crosstab is the shortest way: how many orders per region and month.
import pandas as pd
df = pd.DataFrame({
"Month": ["Jan", "Jan", "Jan", "Feb", "Feb", "Feb", "Feb"],
"Region": ["North", "South", "North", "South", "North", "East", "East"],
"Sales": [120, 340, 410, 95, 150, 80, 60],
})
print(pd.crosstab(df["Region"], df["Month"], margins=True))Month Feb Jan All Region East 2 0 2 North 1 2 3 South 1 1 2 All 4 3 7
Filters, then saving
The Filters box is just a filter on the data first, for example only rows with sales of at least 100. Then save the pivot to Excel; the row labels are part of the table, so keep the index this time.
big = df[df["Sales"] >= 100]
pt = pd.pivot_table(big, index="Region", columns="Month",
values="Sales", aggfunc="sum", fill_value=0)
pt.to_excel("pivot.xlsx") # keep the index: it holds the region names✎ Exercise
Build a pivot with Store as rows, Day as columns and the sum of Visitors, with 0 in empty cells and a Total row and column. Print it.
Hint: pd.pivot_table(df, index=..., columns=..., values=..., aggfunc="sum", fill_value=0, margins=True, margins_name="Total")
import pandas as pd
df = pd.DataFrame({
"Store": ["Oslo", "Riga", "Oslo", "Riga", "Oslo", "Kyiv"],
"Day": ["Mon", "Mon", "Tue", "Tue", "Tue", "Mon"],
"Visitors": [30, 22, 41, 18, 9, 27],
})
# your code here
Expected output:
Day Mon Tue Total Store Kyiv 27 0 27 Oslo 30 50 80 Riga 22 18 40 Total 79 68 147
Show a solution
import pandas as pd
df = pd.DataFrame({
"Store": ["Oslo", "Riga", "Oslo", "Riga", "Oslo", "Kyiv"],
"Day": ["Mon", "Mon", "Tue", "Tue", "Tue", "Mon"],
"Visitors": [30, 22, 41, 18, 9, 27],
})
pt = pd.pivot_table(df, index="Store", columns="Day", values="Visitors",
aggfunc="sum", fill_value=0, margins=True,
margins_name="Total")
print(pt)Day Mon Tue Total Store Kyiv 27 0 27 Oslo 30 50 80 Riga 22 18 40 Total 79 68 147
Check yourself
1. Which pivot_table argument is the Rows box of an Excel pivot?
index sets the row labels.
2. How do you add Grand Totals?
margins=True adds a total row and column; margins_name renames them.
3. How do you apply a pivot table Filter in pandas?
Filter rows first with a mask, then pivot the result.