Sub topic 3
Controlling melt: id_vars, value_vars, var_name and value_name
This chapter assumes you can build a DataFrame, select columns with [], and have seen melt turn columns into rows. Here you will learn the four arguments that decide what melt keeps, what it stacks, and what it calls the results.
The four arguments
melt splits your columns into two groups and renames the two output columns.
| Argument | What it does | Default |
|---|---|---|
| `id_vars` | Columns kept as they are and repeated on every output row | None, so every column is melted |
| `value_vars` | Columns stacked into rows | All columns not in `id_vars` |
| `var_name` | Name of the new column that holds the old column labels | `"variable"` |
| `value_name` | Name of the new column that holds the cell values | `"value"` |
Keeping several identifier columns
Pass a list to id_vars when more than one column describes the row.
import pandas as pd
wide = pd.DataFrame({
"store": ["A", "B"],
"region": ["north", "south"],
"jan": [100, 80],
"feb": [110, 90],
"mar": [120, 95],
})
long = wide.melt(
id_vars=["store", "region"],
var_name="month",
value_name="sales",
)
print(long)Because value_vars is omitted, jan, feb and mar are all stacked. The result has six rows: two stores times three months. The rows come out column by column, so both January rows come first, then both February rows.
Melting only some columns
Use value_vars to stack a subset. Columns that are in neither list are dropped.
quarter_start = wide.melt(
id_vars=["store", "region"],
value_vars=["jan", "feb"],
var_name="month",
value_name="sales",
)
print(quarter_start)This returns four rows, and mar does not appear. If you want to keep a column unchanged without stacking it, it must be in id_vars. Leaving it out of both lists discards it.
Naming the output columns
The defaults variable and value say nothing about your data. Set var_name and value_name every time, because later steps such as groupby("month") read much better with real names.
If your wide table has a name on its column axis, melt uses it as the default var_name. Check wide.columns.name when the label column has a surprising name.
Common errors
- KeyError on a column. Every name in
id_varsandvalue_varsmust exist in the DataFrame. A typo or stray space in a header raisesKeyError. - Mixed dtypes in the value column. All stacked columns share one output column. If you melt integer and string columns together, the result has
objectdtype and numeric operations fail. Melt columns that hold the same kind of measurement. - Index not preserved. By default
meltresets the index to 0, 1, 2 and so on. If the original index matters, move it into a column withreset_index()first and list it inid_vars, or passignore_index=False. Withignore_index=Falsethe original labels repeat, once per melted column. - Overlapping lists. Putting the same column in both
id_varsandvalue_varsis a mistake that produces confusing output. Keep the two lists disjoint.
Selecting value columns by pattern
When a table has many measurement columns, build the list instead of typing it.
month_cols = [c for c in wide.columns if c not in ("store", "region")]
long = wide.melt(
id_vars=["store", "region"],
value_vars=month_cols,
var_name="month",
value_name="sales",
)
print(long.shape)This prints (6, 4): six rows and four columns (store, region, month, sales).
Exercise
A DataFrame has columns id, name, q1, q2, q3 and q4. You want one row per id and quarter, with the quarter in a column called quarter and the numbers in a column called revenue. The name column should be dropped. Which melt call does this, and how many rows result for 10 ids?
Show answer
df.melt(idvars="id", valuevars=["q1", "q2", "q3", "q4"], varname="quarter", valuename="revenue"). Because name is in neither idvars nor valuevars, it is dropped. The result has 10 × 4 = 40 rows.