Pivot Tables, Melt, Stack, and Unstack

Pandas Basics

2 min read

Published Sep 29 2025, updated Aug 17 2026


21
0
0
0

PandasPython

There are various ways to reshape your data between wide, long, and hierarchical forms.

  • Pivot Table → reshapes data from long → wide, useful for summarisation (like Excel pivot tables).
  • Melt → reshapes data from wide → long, useful for tidy data & plotting.
  • Stack → Takes columns and “stacks” them into the row index.
  • Unstack → Moves an index level back into columns.



Pivot Table

A pivot table summarises and reshapes data by aggregating values across one or more categories.


Syntax:

pd.pivot_table(    data,    values=None,    index=None,    columns=None,    aggfunc="mean",    fill_value=None,    margins=False)

Key Parameters:

  • data → DataFrame
  • values → column(s) to aggregate
  • index → row grouping
  • columns → column grouping
  • aggfunc → aggregation function ('mean', 'sum', 'count', custom funcs)
  • fill_value → replace missing values in result
  • margins=True → adds totals (like Excel “All”)

Example:

import pandas as pddata = {    "Department": ["Sales", "Sales", "IT", "IT", "HR"],    "Employee": ["Alice", "Bob", "Charlie", "Dave", "Eve"],    "Salary": [50000, 60000, 70000, 80000, 45000],}df = pd.DataFrame(data)pivot = pd.pivot_table(    df,    values="Salary",    index="Department",    aggfunc="mean")print(pivot)

Output:

             SalaryDepartment         HR            45000IT            75000Sales         55000





Melt

melt() is the reverse of pivot. It transforms a wide DataFrame into a long (tidy) format.


Syntax:

pd.melt(    frame,    id_vars=None,    value_vars=None,    var_name="variable",    value_name="value")

Key Parameters:

  • frame → DataFrame
  • id_vars → columns to keep fixed (like identifiers)
  • value_vars → columns to unpivot
  • var_name → new column name for variable names
  • value_name → new column name for values

Example:

df = pd.DataFrame({    "Employee": ["Alice", "Bob"],    "Sales_Q1": [200, 150],    "Sales_Q2": [210, 160]})melted = pd.melt(    df,    id_vars=["Employee"],    value_vars=["Sales_Q1", "Sales_Q2"],    var_name="Quarter",    value_name="Sales")print(melted)

Output:

  Employee   Quarter  Sales0    Alice  Sales_Q1    2001      Bob  Sales_Q1    1502    Alice  Sales_Q2    2103      Bob  Sales_Q2    160





Stack

Takes columns and “stacks” them into the row index. Useful for moving from a wide to a longer DataFrame, especially when you already have a MultiIndex.


Example:

import pandas as pddf = pd.DataFrame({    "Name": ["Alice", "Bob"],    "Math": [90, 80],    "Science": [85, 95]})print("Original DF:\n", df)stacked = df.set_index("Name").stack()print("\nStacked:\n", stacked)


Output:

Original DF:     Name  Math  Science0  Alice    90       851    Bob    80       95Stacked:Name     Alice  Math       90       Science    85Bob    Math       80       Science    95dtype: int64

Notice how Math and Science moved into the row index. The result is a Series with a MultiIndex




Unstack

Moves an index level back into columns and restores the wider form.


Example:

unstacked = stacked.unstack()print(unstacked)

Output:

       Math  ScienceName                  Alice     90       85Bob       80       95
© 2025 SimpleSteps.guide
AboutFAQPoliciesContact
Pandas Basics | Pivot Tables, Melt, Stack, and Unstack | SimpleSteps.guide