typestar

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

  1. index becomes the rows, columns the columns, values the cells.
  2. aggfunc decides what happens when a cell has several rows.
  3. fill_value replaces the gaps the reshape leaves behind.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 4 in Reshaping & joining, step 21 of 26 in pandas.

← Previous Next →