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 read the output of DataFrame.melt in its simplest form. The earlier chapter showed melt turning columns into rows. Here you will control which columns stay fixed, which are stacked, and what the output columns are called. You will also see the edge cases that surprise people: dropped columns, mixed dtypes, repeated indexes and name collisions.
All code blocks below share one starting DataFrame, which the first block defines. Run them in order in a single session.
The four parameters
melt splits the columns of a DataFrame into three groups.
| Parameter | Role | Default when omitted |
|---|---|---|
| `id_vars` | Columns kept as they are and repeated for every stacked value | None. No column is kept. |
| `value_vars` | Columns whose headers and values are stacked | Every column not listed in `id_vars` |
| `var_name` | Name of the new column that holds the old column headers | `"variable"`, or the name of the columns axis if it has one |
| `value_name` | Name of the new column that holds the stacked values | `"value"` |
Any column that appears in neither id_vars nor value_vars is dropped from the result. That only happens when you list value_vars explicitly. If you omit value_vars, everything outside id_vars is stacked.
Starting with a wider frame
The frame below has an identifier (store), a descriptive column (region) and three month columns.
import pandas as pd
wide = pd.DataFrame({
"store": ["A", "B"],
"region": ["East", "West"],
"jan": [100, 80],
"feb": [110, 90],
"mar": [120, 95],
})
default = wide.melt(id_vars=["store", "region"])
print(default)
print(default.shape)Here id_vars is a list, so both identifier columns survive. The three month columns are stacked, so the result has 2 stores × 3 months = 6 rows and four columns: store, region, variable and value. The rows come out grouped by original column: both jan rows first, then both feb rows, then both mar rows.
The default names variable and value say nothing about the data. Rename them in the same call rather than afterwards.
Naming the output columns
named = wide.melt(
id_vars=["store", "region"],
var_name="month",
value_name="sales",
)
print(named.columns.tolist())The columns are now ["store", "region", "month", "sales"]. Choose names that describe what the old headers meant (month) and what the cells measured (sales). Later steps such as groupby("month") or a pivot back to wide read much better with real names.
The columns axis name
If the columns axis already has a name, melt uses it for the variable column when you don't pass var_name. This happens often after a pivot, which sets that name for you.
named_axis = wide.set_index(["store", "region"]).rename_axis(columns="month")
print(named_axis.reset_index().melt(id_vars=["store", "region"]).columns.tolist())The output columns are store, region, month and value. An explicit var_name always wins over the axis name. If the result shows an unexpected variable or a surprising name, check df.columns.name.
Choosing which columns to stack
Often only some columns should be unpivoted. Use value_vars to say which.
subset = wide.melt(
id_vars="store",
value_vars=["jan", "feb"],
var_name="month",
value_name="sales",
)
print(subset)The result has four rows: store A and B for jan, then for feb. Two things to notice:
regionis gone, because it is in neitherid_varsnorvalue_vars.maris gone, because it was not listed invalue_vars.
This silent dropping is useful for a quick view of a few columns. It also hides mistakes. If a result is missing a column you expected, check whether you passed value_vars and forgot to include it in id_vars.
Selecting stacked columns by pattern
When a frame has dozens of measure columns, don't type them out. Build the list from the column names.
month_cols = [c for c in wide.columns if c in {"jan", "feb", "mar"}]
by_pattern = wide.melt(id_vars="store", value_vars=month_cols)
print(by_pattern["variable"].unique())The same idea works with wide.columns[2:], wide.filter(regex="^(jan|feb|mar)$").columns or wide.select_dtypes("number").columns. Build the list in your own code and pass it, so the selection is visible and easy to change.
Missing names raise an error
If id_vars or value_vars names a column that doesn't exist, melt raises a KeyError that lists the missing names. A typo such as "Jan" for "jan" fails loudly. Silent dropping only applies to columns you never mentioned.
Melting without id_vars
If you omit id_vars, nothing is kept. Every row of the result is just a header and a value.
months_only = wide[["jan", "feb", "mar"]].melt()
print(months_only)The result has six rows and two columns, variable and value. Which store each value came from is lost. This is fine for a single distribution plot of all values, or for counting values per header. It is rarely what you want for analysis that must trace a value back to its row.
Calling wide.melt() with no arguments at all stacks every column, including store and region. That gives ten rows (5 columns × 2 rows) and almost always a mistake.
What happens to the index
By default melt discards the original index and builds a fresh 0, 1, 2, .... Pass ignore_index=False to keep the original index labels.
kept = wide.melt(
id_vars="store",
value_vars=["jan", "feb"],
ignore_index=False,
)
print(kept.index.tolist())The index is [0, 1, 0, 1]. Each original row label repeats once per stacked column, so the index is no longer unique. This lets you join results back to the original frame by label, for example wide.join(kept["value"], rsuffix="_long"). Unique-index assumptions in later code, such as .loc[0] returning a single row, will stop holding. If your original index carries meaning, such as a timestamp or an ID, it is better to move it into a column with reset_index() and list it in id_vars.
Pitfalls
Mixed dtypes in the value column
All stacked values go into one column, so that column needs one dtype. If you stack columns of different types, pandas falls back to object.
mixed = wide.melt(id_vars="store", value_vars=["region", "jan"])
print(mixed["value"].dtype)
print(mixed["value"].map(type).unique())The dtype is object, and the column holds both str and int values. Sums, means and comparisons now behave badly or fail. Only stack columns that share a meaning and a type. If the types differ, melt them in separate calls, or convert afterward with pd.to_numeric.
Even with all-integer columns, one missing value changes the dtype. A NaN forces the column to float64 unless you use a nullable dtype such as Int64.
Missing values are kept
melt doesn't drop NaN values. A missing cell in the wide frame becomes a row with a NaN in the value column. If the wide layout used NaN to mean "not measured", remove those rows explicitly:
holes = wide.copy()
holes.loc[1, "mar"] = None
clean = holes.melt(id_vars="store", value_vars=["jan", "mar"]).dropna(subset=["value"])
print(len(clean))Without dropna there would be four rows. With it, three remain.
Name collisions
The new column names must not match a column that is kept. Pandas raises a ValueError in recent versions if value_name equals an existing column name.
try:
wide.melt(id_vars="store", value_vars=["jan"], value_name="store")
except ValueError as err:
print("melt failed:", type(err).__name__)The call fails because the result would have two columns called store. Pick a name that isn't already in id_vars. The same care applies to var_name. A name that clashes with a kept column gives confusing results or an error.
MultiIndex columns
When the columns are a MultiIndex, melt stacks one level at a time. The col_level parameter chooses which level supplies the headers, and var_name can take a list of names to keep every level as a separate column. Flattening the columns first is the simpler route for most data. Chapter sections on MultiIndex columns cover this later.
Choosing parameters: a checklist
- List the columns that identify a row (store, date, ID) and pass them as
id_vars. Include every descriptive column you want to keep. - Decide whether all the remaining columns are the same kind of measure. If so, omit
value_vars. If not, list the ones to stack, and accept that unlisted columns disappear. - Always set
var_nameandvalue_nameto descriptive names that don't collide withid_vars. - Check the result's
dtypes, its shape (rows × stacked columns) and whether you needignore_index=Falseor adropnastep.
Exercise
A DataFrame df has the columns id, q1, q2, q3 and comment. You want a long table with only the first two quarters, with columns named id, quarter and revenue. Write the melt call. Which column disappears from the result, and why?
Show answer
df.melt(idvars="id", valuevars=["q1", "q2"], varname="quarter", valuename="revenue"). The comment column disappears because it is in neither idvars nor valuevars. The q3 column is also dropped for the same reason. The result has two rows for each original row, one for q1 and one for q2.
Exercise
You run df.melt(id_vars="id", value_vars=["name", "score"]), where name holds text and score holds integers. What is the dtype of the value column, and how would you avoid the problem?
Show answer
The value column has dtype object, because it mixes strings and integers. Avoid it by melting only columns of one type. Keep name in idvars if it identifies the row, and put only score in valuevars.