Convert wide tables to tidy long data
Normalize tables where separate measurement columns represent categories such as months, metrics, or statuses.
Pandas · Function
pandas.melt reshapes a DataFrame from wide to long format. It preserves selected identifier columns and unpivots measured columns into variable and value columns.
pandas.melt reshapes a DataFrame from wide to long form. Columns listed in id_vars remain as identifiers; selected measured columns become a variable column and a value column, with optional control over their names, MultiIndex column level, and index retention.
pandas.melt(frame, id_vars=None, value_vars=None, var_name=None, value_name='value', col_level=None, ignore_index=True)| Name | Type | Description |
|---|---|---|
frame | DataFrame | DataFrame to reshape from wide to long form. |
id_vars | scalar, tuple, list, or ndarray, optional | Columns to keep as identifier variables. |
value_vars | scalar, tuple, list, or ndarray, optional | Columns to unpivot; when omitted, all columns not in id_vars are used. |
var_name | scalar, optional | Name for the output variable column; defaults from frame.columns.name or variable. |
value_name | scalar, optional | Name for the output value column; defaults to value and cannot already be a column label. |
col_level | scalar, optional | MultiIndex column level to melt. |
ignore_index | bool, optional | Whether to ignore the original index; defaults to True. |
DataFrame
import pandas as pd
wide = pd.DataFrame({
"city": ["Paris", "Berlin"],
"jan": [10, 12],
"feb": [11, 13],
})
long = pd.melt(
wide,
id_vars=["city"],
value_vars=["jan", "feb"],
var_name="month",
value_name="temperature",
)
print(long)This converts the month columns into rows while retaining city as the identifier.
Normalize tables where separate measurement columns represent categories such as months, metrics, or statuses.
Prepare data for grouped analysis or visualization libraries that expect one observation per row.
Reshape tables with hierarchical column labels by selecting the relevant MultiIndex level.
It reshapes wide data into long data. Identifier columns stay in place, while measured columns are converted into rows represented by variable and value columns.
Follow-up: How are measured columns chosen when value_vars is omitted? All columns not listed in id_vars are used.
id_vars identifies columns to keep unchanged as identifiers. value_vars selects the columns to unpivot; if omitted, every column not in id_vars is unpivoted.
Follow-up: How would you keep several identifying fields? Pass them together as a list or tuple to id_vars.
By default, melt creates variable and value columns and discards the original index. var_name and value_name customize those columns, while ignore_index=False retains the original index.
Follow-up: What if the input has MultiIndex columns? Use col_level to choose the level to melt.
DataFrame.meltDataFrame.pivotDataFrame.pivot_tablepandas.wide_to_long