🐼 Python Pandas examples

pandas melt Examples

Unpivot wide tables into long format for charts and analysis.

Updated 2026-06-125 practical examplesCopy-ready code

💡 Ideas for You

Learning resources for Python Pandas, data cleaning and analysis.

4 useful links

Some links in this section may be affiliate links. Choose only what is useful for your own work.

Sample DataFrame context

A monthly report with one column per month.

Syntax or pattern

df.melt(id_vars="product", var_name="month", value_name="sales")
✍️

5 practical examples

1

Unpivot monthly columns

Turn Jan, Feb and Mar columns into rows.

long = df.melt(id_vars="product", var_name="month", value_name="sales")

The data becomes easier to group, chart and filter.

2

Create a revenue matrix

Place regions as rows and months as columns.

matrix = pd.pivot_table(sales, values="revenue", index="region", columns="month", aggfunc="sum", fill_value=0)

The result is an Excel-like summary table.

3

Reset the index after reshaping

Return a grouped or pivoted output to normal columns.

output = matrix.reset_index()

The output can be exported or merged with other tables.

4

Split list values into rows

Use explode for tags or product lists.

expanded = df.explode("tags")

Each tag gets its own row for filtering or counting.

5

Validate reshaped totals

Compare totals before and after reshaping.

df["sales"].sum(), long["sales"].sum()

Matching totals help confirm the reshape did not lose values.

Common mistakes to avoid

  • Changing the original DataFrame before checking the result.
  • Forgetting to inspect row counts before and after the operation.
  • Using a pattern without confirming column names and data types.

FAQ

What is the main use of melt Examples?

Unpivot wide tables into long format for charts and analysis.

Should I use this in a notebook or a script?

Both work. Use a notebook while exploring the data, then move the final workflow into a repeatable script when it is stable.

How do I avoid breaking my source data?

Create a copy of the DataFrame before transforming it and check row counts, missing values and sample rows after each important step.