Learn Pandas · 12/14

Reshaping and Pivoting Data

7 min read

Hello there! Welcome to the Pandas section on Reshaping and Pivoting. Grab a cup of coffee ☕, and let's untangle some messy data together.

You've done the hard work of loading your data. But wait... it looks like it was assembled by a committee of caffeine-deprived squirrels. The columns are where the rows should be, the rows are where the columns should be, and it's just not in a "happy little DataFrame" format.

The Problem: Raw data is often structured for storage or data entry, not for analysis. To perform meaningful analysis, plotting, or machine learning, you need to rearrange, or "reshape," the data into a tidy format.

The Solution: Pandas provides a powerful set of functions to twist, turn, and reshape your data into the perfect structure for your needs. Let's dive into the most common reshaping tools you'll use in the industry.


1. Creating Excel-style Pivot Tables: pivot_table()

Imagine you have a long list of sales records, but your manager wants a summary table showing total sales for each product category across different regions. This is a classic "pivot" operation.

The pivot_table() function is your go-to tool for this. It takes your long-format data and creates a wide-format summary table, just like in a spreadsheet. It's incredibly powerful because it can aggregate data (sum, mean, count, etc.) during the reshaping process.

Key Arguments You'll Actually Use:

  • data: The DataFrame you're working with.
  • index: The column(s) whose unique values will become the rows of your new table.
  • columns: The column(s) whose unique values will become the columns of your new table.
  • values: The column whose data will populate the cells of the new table.
  • aggfunc: The function to use for aggregation if you have multiple entries for an index/column pair (e.g., 'sum', 'mean', 'count'). The default is 'mean'.

Example in Action 🚀

Let's say we have sales data for a small online store.

python
import pandas as pd

df = pd.DataFrame({
    "Region": ["North", "West", "North", "South", "West", "South"],
    "Category": ["Apparel", "Apparel", "Shoes", "Apparel", "Shoes", "Shoes"],
    "Sales": [150, 200, 100, 250, 150, 300]
})

print("Original Data:")
print(df)

Original Data:

apache
  Region Category  Sales
0  North  Apparel    150
1   West  Apparel    200
2  North    Shoes    100
3  South  Apparel    250
4   West    Shoes    150
5  South    Shoes    300

Now, let's create a pivot table to see total sales by Region and Category.

python
pivot_df = pd.pivot_table(
    df,
    index="Region",
    columns="Category",
    values="Sales",
    aggfunc="sum"
)

print("\nPivot Table:")
print(pivot_df)

Pivot Table:

apache
Category  Apparel  Shoes
Region
North       150.0  100.0
South       250.0  300.0
West        200.0  150.0

Voilà! A clean, summarized table perfect for a report. You can also get row and column totals by adding margins=True.


2. Wide to Long Format: Melting DataFrames with melt()

Sometimes you have the opposite problem. Your data is too wide. Imagine columns like Jan_Sales, Feb_Sales, Mar_Sales, etc. This format is not ideal for many types of analysis, especially time-series plotting. We need to "unpivot" it.

This is where melt() comes in. It takes your wide DataFrame and turns it into a long one, making it much more flexible. Think of it as melting a wide, solid block of data into a long, flowing stream.

Key Arguments You'll Actually Use:

  • id_vars: The column(s) you want to keep as they are (your identifiers).
  • value_vars: The column(s) you want to "unpivot" or turn into rows. If you leave this blank, it will use all columns not in id_vars.
  • var_name: The name for the new column that holds the headers from value_vars.
  • value_name: The name for the new column that holds the values.

Example in Action 💧

Let's take a dataset of quarterly sales.

python
df_wide = pd.DataFrame({
    "Product": ["A", "B", "C"],
    "Q1_Sales": [100, 150, 50],
    "Q2_Sales": [110, 160, 60],
    "Q3_Sales": [120, 170, 70]
})

print("Wide Data:")
print(df_wide)

Wide Data:

apache
  Product  Q1_Sales  Q2_Sales  Q3_Sales
0       A       100       110       120
1       B       150       160       170
2       C        50        60        70

This is hard to plot. Let's melt it!

python
df_long = pd.melt(
    df_wide,
    id_vars=["Product"],
    value_vars=["Q1_Sales", "Q2_Sales", "Q3_Sales"],
    var_name="Quarter",
    value_name="Sales"
)

print("\nLong (Melted) Data:")
print(df_long)

Long (Melted) Data:

apache
  Product   Quarter  Sales
0       A  Q1_Sales    100
1       B  Q1_Sales    150
2       C  Q1_Sales     50
3       A  Q2_Sales    110
4       B  Q2_Sales    160
5       C  Q2_Sales     60
6       A  Q3_Sales    120
7       B  Q3_Sales    170
8       C  Q3_Sales     70

Much better! Now this data is ready for analysis and visualization.


3. Hierarchical Data: Stacking and Unstacking

What if your columns or rows have multiple levels? This is called a MultiIndex. It's a bit like having sub-categories for your rows or columns. stack() and unstack() are the primary tools for manipulating these hierarchical levels.

  • stack(): Pivots a level of the column labels into the row index, making the DataFrame taller (longer).
  • unstack(): The inverse of stack. It pivots a level of the row index into the column labels, making the DataFrame wider.

Analogy: The Filing Cabinet 🗄️

Imagine your DataFrame is a filing cabinet.

  • stack() is like taking the labels off the top of the drawers (columns) and turning them into a new set of nested folders (index). Your cabinet gets narrower but deeper.
  • unstack() is like taking a level of folders out (index) and making them into new drawers (columns). Your cabinet gets wider but shallower.

Example in Action 📚

Let's use the pivot table we created earlier, which has a simple column index.

python
print("Original Pivot Table:")
print(pivot_df)

Original Pivot Table:

apache
Category  Apparel  Shoes
Region
North       150.0  100.0
South       250.0  300.0
West        200.0  150.0

Now, let's stack it. This will move the Category level from the columns to the index.

python
stacked_df = pivot_df.stack()

print("\nStacked DataFrame:")
print(stacked_df)

Stacked DataFrame:

apache
Region  Category
North   Apparel     150.0
        Shoes       100.0
South   Apparel     250.0
        Shoes       300.0
West    Apparel     200.0
        Shoes       150.0
dtype: float64

Notice it's now a Series with a MultiIndex. To go back, we just unstack it.

python
unstacked_df = stacked_df.unstack()

print("\nUnstacked DataFrame:")
print(unstacked_df)

Unstacked DataFrame:

apache
Category  Apparel  Shoes
Region
North       150.0  100.0
South       250.0  300.0
West        200.0  150.0

And we're right back where we started!


4. Frequency Tables: Using crosstab()

Sometimes you just want to know "how many times does A appear with B?" You want a simple frequency count between two or more categorical variables. This is called a cross-tabulation or a contingency table.

While you could achieve this with groupby().count(), the pd.crosstab() function is a much more direct and convenient tool for this specific job.

Key Arguments You'll Actually Use:

  • index: The values to group by in the rows.
  • columns: The values to group by in the columns.
  • margins: A boolean to add row and column totals.
  • normalize: Set to True or 'index' or 'columns' to show percentages instead of counts.

Example in Action 📊

Using our original sales data, let's see how many transactions (the count of rows) occurred for each Category in each Region.

python
print("Original Data:")
print(df)

Original Data:

apache
  Region Category  Sales
0  North  Apparel    150
1   West  Apparel    200
2  North    Shoes    100
3  South  Apparel    250
4   West    Shoes    150
5  South    Shoes    300

Let's create a frequency table.

python
freq_table = pd.crosstab(
    index=df["Region"],
    columns=df["Category"],
    margins=True,
    margins_name="Total" # Let's give the margin a nice name!
)

print("\nFrequency Crosstab:")
print(freq_table)

Frequency Crosstab:

apache
Category  Apparel  Shoes  Total
Region
North           1      1      2
South           1      1      2
West            1      1      2
Total           3      3      6

This instantly tells us the frequency distribution. For example, there was 1 transaction for Apparel in the North region. It's a quick and easy way to see relationships between categorical variables.


📚 References for Extra Reading

Challenge

You are given a Pandas DataFrame df_quarterly_sales that contains store revenue data in a wide format, with each quarter's revenue in a separate column. Your task is to reshape and analyze this data using three different Pandas functions.

Task 1: Unpivot the Data
First, transform the df_quarterly_sales DataFrame from its wide format into a long format using the melt() function.

  • Assign the resulting DataFrame to a new variable called df_long.
  • The columns Region, Store_Manager, and Store_Type should be kept as identifier variables.
  • The new column containing the names of the original quarter columns (Q1_Revenue, Q2_Revenue, etc.) should be named Quarter.
  • The new column containing the revenue values should be named Revenue.

Task 2: Create a Summary Pivot Table
Next, using the df_long DataFrame you created in Task 1, generate a pivot table to summarize the data.

  • Assign the pivot table to a new variable called pivot_summary.
  • The table should calculate the average revenue for each group.
  • Set Region as the index and Store_Type as the columns.

Task 3: Build a Frequency Table
Finally, using the original df_quarterly_sales DataFrame, create a frequency table to count the number of stores.

  • Assign the frequency table to a new variable called crosstab_freq.
  • The table should show the distribution of Store_Type across each Region.
  • Ensure that you include the marginal totals (sum for each row and column).

Expected result

Your code must define three specific Pandas objects with the correct structure and data.

  1. df_long: A DataFrame in 'long' or 'tidy' format. It must have 32 rows and 5 columns named Region, Store_Manager, Store_Type, Quarter, and Revenue.

  2. pivot_summary: A pivot table summarizing the long-form data.

    • Index: Region
    • Columns: Store_Type
    • Values: The average Revenue.
    • The resulting shape should be 4 rows by 2 columns.
  3. crosstab_freq: A frequency table created from the original data.

    • Index: Region
    • Columns: Store_Type
    • Values: The count of stores.
    • It must include row and column totals (margins).
    • The resulting shape should be 5 rows by 3 columns (including the total row and column).
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.