melt() (Pandas)
pd.melt() reshapes a wide DataFrame into a long, tidy one by collapsing several columns into two: a 'variable' column holding the old column names and a 'value' column holding their values.
Pandas
melt is the inverse of pivot. You keep some columns fixed as identifiers (id_vars) and unpivot the rest into name/value pairs. This 'long' or 'tidy' shape — one observation per row — is exactly what plotting libraries and groupby operations prefer.
Use value_vars to melt only a subset of columns, and rename the output columns with var_name and value_name for clarity. A frame with one row per subject and many measurement columns becomes many rows, one per subject-measurement.
Melt to tidy data for analysis and plotting; pivot or pivot_table to go back to a wide, human-readable report layout.
Syntax
pd.melt(df, id_vars=None, value_vars=None, var_name=None, value_name='value')Examples
Python
import pandas as pd
df = pd.DataFrame({"id": [1], "a": [10], "b": [20]})
print(pd.melt(df, id_vars="id"))Output:
id variable value
0 1 a 10
1 1 b 20