Pivoting in Python
pivot_table reshapes long data into a grid, aggregating where keys repeat.
import pandas as pd
frame = pd.DataFrame({
"day": ["mon", "mon", "tue", "tue"],
"lang": ["python", "rust", "python", "sql"],
"tpm": [104, 98, 91, 79],
})
grid = frame.pivot_table(index="day", columns="lang", values="tpm",
aggfunc="mean", fill_value=0)
print(grid)
print(grid.columns.tolist(), grid.index.tolist())
How it works
indexbecomes the rows,columnsthe columns,valuesthe cells.aggfuncdecides what happens when a cell has several rows.fill_valuereplaces the gaps the reshape leaves behind.
Keywords and builtins used here
asprint
The run, in numbers
- Lines
- 12
- Characters to type
- 315
- Tokens
- 127
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 69 seconds.
Step 3 of 4 in Reshaping & joining, step 21 of 26 in pandas.