Data Science

Reshaping Data with Pivot and Melt

SQL Mastery Team
May 14, 2026
6 min read

Welcome to **Day 113**. Today we learn how to "Pivot."

The "Wide" vs "Long" Debate

  • **Long Format**: Every row is a single observation. (Better for machines/databases).
  • **Wide Format**: Categories are spread across columns. (Better for humans/Excel).
  • Pivoting (Long to Wide)

    # Turn categories into columns

    wide_df = df.pivot(index='date', columns='category', values='revenue')

    Melting (Wide to Long)

    # The inverse! Turn columns back into rows

    long_df = pd.melt(wide_df, id_vars=['date'], var_name='category', value_name='revenue')

    Why this is advanced

    Pivoting allows you to compare categories side-by-side (e.g., "Sales of Apples" vs "Sales of Oranges" per day). It's the secret to building high-level summary tables.

    Your Task for Today

    Take a multi-category dataset and pivot it so that dates are rows and categories are columns.

    *Day 114: Handling DateTime in Pandas.*

    Ready to put your knowledge into practice?

    Join SQL Mastery and learn through interactive exercises.