Skip to content
Pandas

Pivot Tables

Reshape data with pivot, melt, and pivot_table.

By EZ4Code Team
pivotreshapemelt

Code

import pandas as pd

df = pd.DataFrame({
    "date": ["2024-01", "2024-01", "2024-02", "2024-02"],
    "city": ["NYC", "LA", "NYC", "LA"],
    "sales": [100, 80, 120, 90],
})

# Wide format: one row per date, one column per city
wide = df.pivot(index="date", columns="city", values="sales")

# Aggregating pivot handles duplicates
pv = df.pivot_table(index="date", columns="city",
                    values="sales", aggfunc="sum", margins=True)

# Melt back to long
long = wide.reset_index().melt(id_vars="date", var_name="city",
                               value_name="sales")
print(wide, pv, long)

Explanation

pivot reshapes long data into wide form using unique combinations as cells; pivot_table additionally aggregates duplicates. melt is the inverse, melting columns back into key-value pairs for tidy data. The margins argument adds row and column totals to a pivot table.

More Pandas Snippets