pivot_table()
noun
say it: “PIV-ut TAY-bul” /ˈpɪvət ˈteɪbəl/
A pandas method that builds a grid summary from a table: the rows from one column, the columns from another, and a total or average in each cell.
What does pivot_table() do in pandas?
pivot_table() is the pandas method that builds a pivot table: index names the column down the side, columns
the one across the top, values the numbers to summarize and aggfunc how (a sum, a mean, a count). fill_value
fills empty squares and margins=True adds the totals.
import pandas as pd
orders = pd.DataFrame({"weekday": ["Fri", "Fri", "Sat"], "size": ["small", "large", "large"], "total": [12.0, 20.0, 22.0]})
grid = orders.pivot_table(index="weekday", columns="size", values="total",
aggfunc="sum", fill_value=0, margins=True)
print(grid)
# size large small All
# weekday
# Fri 20.0 12.0 32.0
# Sat 22.0 0.0 22.0
# All 42.0 12.0 54.0
In a sentence
- “She filled the empty squares with zeros through the fill_value of pivot_table().”
- “pivot_table() with margins=True added a total row and a total column.”
Level: Journeyman · More Python terms at this level
Updated