Skip to main content

Melt and Wide to Long - Unpivoting a Pivot

Pandas provides two methods for converting DataFrames from wide to long format (unpivoting).

Melt Method

Unpivot a DataFrame from wide to long format, optionally leaving identifiers set.
df.melt()
The melt function provides flexibility when restructuring data from a wide format into a long format, allowing you to specify which columns serve as identifiers and which become variable-value pairs.
Use melt when you need fine-grained control over which columns become identifiers and which become variable-value pairs.
Documentation: pandas.melt

Wide to Long Method

Unpivot a DataFrame from wide to long format. Less flexible but more user-friendly than melt.
pd.wide_to_long()
The wide_to_long function offers a more accessible alternative to melt, trading some flexibility for improved usability when performing standard unpivoting operations.
Use wide_to_long for simpler, standard unpivoting operations where ease of use is more important than flexibility.
Documentation: pandas.wide_to_long