melt() is the inverse operation of pivot(): id_vars specifies which columns should stay as identifying columns, unchanged, while every other column, or a specific list given in value_vars, gets unpivoted into two new columns — one holding the original column names, var_name, 'variable' by default, and one holding the corresponding values, value_name, 'value' by default. This long format is often what plotting libraries and certain statistical/modeling tools expect, even though a wide format is usually more natural for a human to read directly.
1Understanding pd.melt()
melt() is the inverse operation of pivot(): id_vars specifies which columns should stay as identifying columns, unchanged, while every other column, or a specific list given in value_vars, gets unpivoted into two new columns — one holding the original column names, var_name, 'variable' by default, and one holding the corresponding values, value_name, 'value' by default. This long format is often what plotting libraries and certain statistical/modeling tools expect, even though a wide format is usually more natural for a human to read directly.
Use melt() specifically when a plotting library or modeling tool expects one row per observation in a long format, rather than the wide, one-row-per-subject format that's usually more natural for humans to read directly.
import pandas as pd
df = pd.DataFrame({"name": ["Alice", "Bob"], "math": [90, 85], "science": [95, 80]})
print(pd.melt(df, id_vars=["name"], var_name="subject", value_name="score"))2Practical Example
Here is a real-world application of pd.melt() showing how it is used in production Pandas code.
import pandas as pd
df = pd.DataFrame({"name": ["Alice"], "jan": [100], "feb": [150]})
long_df = pd.melt(df, id_vars=["name"])
print(long_df.shape)3Best Practices
Follow these guidelines when working with pd.melt():
1. Specify id_vars explicitly to control which columns stay fixed as identifiers, rather than relying on defaults that might unpivot columns you actually wanted to keep
2. Give var_name and value_name meaningful custom names instead of the generic defaults, for a more self-documenting result
3. Use melt() before passing data to plotting libraries that expect long-format, one-row-per-observation data
Tip: Use melt() specifically when a plotting library or modeling tool expects one row per observation in a long format, rather than the wide, one-row-per-subject format that's usually more natural for humans to read directly.
import pandas as pd
df = pd.DataFrame({"name": ["Alice", "Bob"], "math": [90, 85], "science": [95, 80]})
print(pd.melt(df, id_vars=["name"], var_name="subject", value_name="score"))