Sub topic 1
Wide versus long: why reshape at all
Prerequisites
This chapter assumes you can do the following:
- Write basic Python and run code in a script or notebook.
- Create a pandas DataFrame and select columns and rows with
[]andloc. - Use
groupbywith aggregations such assumandmean.
It introduces no new pandas functions. It explains the two table layouts that the rest of the tutorial converts between, and how to decide which one a task needs.
Two layouts for the same facts
A table can store the same information in two shapes. In a wide layout, each row describes one entity, and each measurement occupies its own column. In a long layout, each row describes one observation, and a single column holds the measured values.
Here is monthly sales for three stores, first in the wide layout.
import pandas as pd
wide = pd.DataFrame({
"store": ["A", "B", "C"],
"jan": [100, 80, 95],
"feb": [110, 90, 70],
"mar": [120, 85, 105],
})
print(wide)
print(wide.shape)The shape is (3, 4). There is one row per store. The column names jan, feb and mar are really values of a variable, the month. The table does not say that anywhere. You only know it because you can read the names.
Now the same nine measurements in the long layout. This code builds the table by hand so that you can see exactly what it contains. The next chapter shows how melt does it for you.
long = pd.DataFrame({
"store": ["A", "A", "A", "B", "B", "B", "C", "C", "C"],
"month": ["jan", "feb", "mar"] * 3,
"sales": [100, 110, 120, 80, 90, 85, 95, 70, 105],
})
print(long)
print(long.shape)The shape is (9, 3). Each row is one store in one month. Month is now a column with its own name, and every value of sales sits in one column.
| Property | Wide | Long |
|---|---|---|
| Rows | One per entity (store) | One per observation (store and month) |
| Columns | One per measurement (month) | One per variable (store, month, sales) |
| Row count grows when | You add entities | You add entities or measurements |
| Column count grows when | You add measurements | You add new variables |
| Column names hold | Data values (`jan`, `feb`) | Variable names (`month`) |
The idea behind long data
Statisticians call the long form close to "tidy" when it follows three rules:
- Each variable has its own column.
- Each observation has its own row.
- Each kind of observational unit has its own table.
In the wide table above, "month" is a variable, but it is spread across three column headers. That violates rule 1. In the long table, store, month and sales each have a column, and each row is one observation.
"Tidy" is not a synonym for "long" in every case. A wide table is tidy when the columns are different variables, such as height, weight and age for each person. The problem appears only when column names are values of one variable. This chapter's examples all have that problem, which is why long is the target.
Why reshape at all
Neither layout is better in general. Each makes some tasks easy and others awkward. The practical rule is to reshape into whatever layout the next operation expects.
Tasks that favor long data
Grouping works on column values, not on column names. To average sales for each month in the long table, you group by the month column.
months = ["jan", "feb", "mar"]
long["month"] = pd.Categorical(long["month"], categories=months, ordered=True)
print(long.groupby("month", observed=True)["sales"].mean())The categorical conversion matters. Without it, groupby sorts the month labels as strings, and you get feb, jan, mar instead of calendar order. Long data makes month an ordinary column, so you can attach an order to it once and every later grouping respects it.
In the wide table, the same average needs a column selection, because the months are names, not values.
print(wide[["jan", "feb", "mar"]].mean())This works for one summary. It gets harder when you want to group by month and by something else, because there is no month column to group by.
Other tools also expect long data:
- Plotting libraries such as seaborn and plotnine map a column to color, facet or x-axis. They need
monthas a column to do that. - Filtering by month is a boolean test on a column (
long["month"] == "feb"), not a choice of column name. - Statistical models and joins work with columns as variables. A merge on
monthrequiresmonthto be a column.
Tasks that favor wide data
Comparisons between measurements in the same row are simpler when each measurement has its own column.
wide["change"] = wide["feb"] - wide["jan"]
print(wide)The change column is 10, 10 and -25. In the long table, you would first need to line up the jan and feb rows for each store before subtracting.
Wide data is also the usual shape for:
- Reports and spreadsheets, where people read across a row.
- Correlation matrices and many machine learning inputs, where each column is a feature and each row is a sample.
- Display, where 200 rows of three columns read worse than 3 rows of 200 columns only if the reader wants to compare across, and better if the reader wants to scan down.
A short decision guide
| You want to... | Prefer |
|---|---|
| Group, filter or plot by the measurement label | Long |
| Compute differences or ratios between measurements per entity | Wide |
| Add a new measurement without changing the table's columns | Long |
| Show a compact cross-tab for a human reader | Wide |
| Pass data to a plotting library that maps columns to aesthetics | Long |
| Feed per-entity features into a model | Wide |
Edge cases to watch for
Adding a measurement changes a wide table's schema
If April data arrives, the wide table needs a new column apr. Any code that lists month columns by hand must change. In the long table, April arrives as new rows, and the code that uses groupby("month") keeps working unchanged. This is the main reason pipelines store data long and reshape to wide only at the end.
Mixed measurement types do not stack cleanly
Suppose each store has both sales (integers) and rating (decimals). If you stack both measurements into one value column, pandas has to give that column a single dtype. The integers are promoted to floats, or the whole column becomes object if text is involved. A column of mixed meaning is also hard to interpret.
The safer pattern is to melt only columns that measure the same quantity in the same unit. Keep sales and rating as separate columns, each with its own dtype.
Missing observations look different
In a wide table, a missing measurement is a NaN in the cell. In a long table, you can either keep a row with NaN or leave the row out entirely. These are not the same. A missing row means "no record." A row with NaN means "a record with no value." When you later convert long to wide, missing rows become NaN cells, so the information that they were absent is preserved only as a missing value.
Size trade-offs
A long table repeats the entity key on every row. Nine values for three stores need store written nine times. For dense data, a wide table usually uses less memory, because it stores each key once. For sparse data, long can be smaller, because absent observations need no row. If memory matters and keys are strings, convert the key column to the category dtype after reshaping.
Column names that carry more than one variable
Names such as score_math and score_art encode two things: the quantity (score) and the subject. Treating the whole name as a single label leaves that structure unsplit. This is a separate reshaping problem, and a later chapter covers it with wide_to_long.
How this tutorial proceeds
The next chapters cover the tools, in this order. The first three go in order of use.
meltconverts wide to long.pivotconverts long to wide when each pair of keys appears once.pivot_tableconverts long to wide when keys repeat, by aggregating them.
After those, the tutorial covers the column labels these calls can produce (MultiIndex columns), and the related tools stack, unstack, wide_to_long and crosstab.
A useful habit before any reshape is to say aloud what one row represents now and what it should represent afterward. For the tables above, "one store" becomes "one store in one month." If you cannot state it, the reshape will probably produce a table you cannot use.
Exercise
A table has the columns city, 2022, 2023 and 2024, where each year column holds the city's population. A teammate wants to plot population over time with one line per city, using a library that maps a column to the x-axis. Which layout should the data be in, which column would hold the year, and what does one row represent?
Show answer
The data should be long. It would have a year column, a population column and a city column. One row represents one city in one year. The library needs year as a column to map to the x-axis, and in the wide layout the years are only column names.
Exercise
Using the wide DataFrame from this chapter (columns store, jan, feb, mar), write one line of code that adds a column best_month_sales holding each store's highest monthly sales. Explain why this is easier in the wide layout than in the long one.
Show answer
wide["best_month_sales"] = wide[["jan", "feb", "mar"]].max(axis=1). Each store's measurements are side by side in one row, so a row-wise max is enough. In the long layout, you would group by store and take the maximum of sales, which also works but needs a grouping step and then a merge or transform to attach the result to each row. If you did the same row-wise operation without listing the month columns, you would also pick up change or any other column you add later.