Ciaren

Unpivot — unpivot

Reshape wide → long (pandas melt).

Use cases

  • Turn Jan/Feb/… columns back into month + value rows.
  • Normalize a wide spreadsheet into a tidy, tall format for grouping.

What it does

Unpivot is the inverse of Pivot: it collapses multiple columns into two columns — one naming the original column (var_name) and one holding the value (value_name).

Unpivot (id_vars=region, value_vars=[Jan,Feb], var_name=month, value_name=amount)
Before
regionJanFeb
North100150
South80200
2 rows · 3 cols
After
regionmonthnewamountnew
NorthJan100
NorthFeb150
SouthJan80
SouthFeb200
4 rows · 3 cols

Configuration

Config keyTypeRequiredDescription
id_varsstring[]YesColumns to keep as identifiers
value_varsstring[]NoColumns to unpivot (defaults to the rest)
var_namestringNoName for the variable column (default variable)
value_namestringNoName for the value column (default value)

Generated Python code

These exports keep region and unpivot every other column using the default output names variable and value. Null values are retained. The illustration above instead names these columns month and amount.

pandas

python
df_2 = df_1.melt(id_vars=['region'])

Polars

python
df_2 = df_1.unpivot(index=['region'])

Tips & common mistakes

  • Leave value_vars empty to unpivot every column that isn't an id_var.
  • Name var_name/value_name meaningfully (e.g. month/amount) for a tidy result.
  • To go the other way (long → wide), use Pivot.

See also