Pivot Tables, Melt, Stack, and Unstack

Pandas Basics

2 min read

Published Sep 29 2025, updated Oct 24 2025


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 pd

data = {
    "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:

             Salary
Department
HR 45000
IT 75000
Sales 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 Sales
0 Alice Sales_Q1 200
1 Bob Sales_Q1 150
2 Alice Sales_Q2 210
3 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 pd

df = 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 Science
0 Alice 90 85
1 Bob 80 95

Stacked:
Name
Alice Math 90
       Science 85
Bob Math 80
       Science 95
dtype: 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 Science
Name
Alice 90 85
Bob 80 95

Products from our shop

Docker Cheat Sheet - Print at Home Designs

Docker Cheat Sheet - Print at Home Designs

Docker Cheat Sheet Mouse Mat

Docker Cheat Sheet Mouse Mat

Docker Cheat Sheet Travel Mug

Docker Cheat Sheet Travel Mug

Docker Cheat Sheet Mug

Docker Cheat Sheet Mug

Vim Cheat Sheet - Print at Home Designs

Vim Cheat Sheet - Print at Home Designs

Vim Cheat Sheet Mouse Mat

Vim Cheat Sheet Mouse Mat

Vim Cheat Sheet Travel Mug

Vim Cheat Sheet Travel Mug

Vim Cheat Sheet Mug

Vim Cheat Sheet Mug

SimpleSteps.guide branded Travel Mug

SimpleSteps.guide branded Travel Mug

Developer Excuse Javascript - Travel Mug

Developer Excuse Javascript - Travel Mug

Developer Excuse Javascript Embroidered T-Shirt - Dark

Developer Excuse Javascript Embroidered T-Shirt - Dark

Developer Excuse Javascript Embroidered T-Shirt - Light

Developer Excuse Javascript Embroidered T-Shirt - Light

Developer Excuse Javascript Mug - White

Developer Excuse Javascript Mug - White

Developer Excuse Javascript Mug - Black

Developer Excuse Javascript Mug - Black

SimpleSteps.guide branded stainless steel water bottle

SimpleSteps.guide branded stainless steel water bottle

Developer Excuse Javascript Hoodie - Light

Developer Excuse Javascript Hoodie - Light

Developer Excuse Javascript Hoodie - Dark

Developer Excuse Javascript Hoodie - Dark

© 2025 SimpleSteps.guide
AboutFAQPoliciesContact