Long to Wide with pivot

The other direction, for when a person should be one row.

pivot spreads a column across the top

It is melt run backwards: the values of one column become column headers.

import pandas as pd

long = pd.DataFrame({"name": ["Ada", "Ada"], "month": ["jan", "feb"], "score": [90, 80]})
wide = long.pivot(index="name", columns="month", values="score")
print(sorted(wide.columns.tolist()))

It needs the pairs to be unique

Two rows for the same person and month give pivot no way to choose, and it raises. pivot_table takes an aggfunc precisely so it can answer that.

import pandas as pd

long = pd.DataFrame({"n": ["a", "a"], "m": ["jan", "jan"], "v": [1, 2]})
out = pd.pivot_table(long, index="n", columns="m", values="v", aggfunc="mean")
print(out.values.tolist())

Exercise

Try It Yourself

Write month_columns(df) that spreads a long table with name, month and score into one row per name, and returns the sorted column names.

Press Run to see output

Check Your Understanding