Wide to Long with melt

Turning a column per month into a column that says which month.

Why long is easier to work with

A table with a column per month cannot be grouped by month, because the month is in the header rather than the data. melt moves it into the rows.

import pandas as pd

wide = pd.DataFrame({"name": ["Ada"], "jan": [90], "feb": [80]})
long = wide.melt(id_vars=["name"], var_name="month", value_name="score")
print(long.shape)
print(long["month"].tolist())

id_vars are what stays put

Everything named in id_vars stays as a column; everything else is folded into the two new columns.

import pandas as pd

wide = pd.DataFrame({"name": ["Ada"], "jan": [90], "feb": [80]})
print(wide.melt(id_vars=["name"]).shape)

Exercise

Try It Yourself

Write to_long(df) that melts a table with a name column and one column per month into columns name, month, score, and returns the row count.

Press Run to see output

Check Your Understanding