Sub topic 1
Wide versus long: why reshape at all
This chapter introduces the two table layouts you will keep meeting in pandas, and explains why you often need to convert one into the other. Later chapters cover the tools that do the conversion.
Prerequisites
This chapter assumes you can do the following:
- Write basic Python syntax.
- Create a pandas DataFrame and index it.
- Select columns and rows with
[]andloc. - Use
groupbywith aggregation functions such assumandmean.
Two layouts for the same data
A table in wide layout spreads one kind of measurement across several columns. A table in long layout stores that measurement in a single column and uses another column to say what each value means.
Here is the same sales data in both layouts.
import pandas as pd
wide = pd.DataFrame({
"store": ["A", "B"],
"jan": [100, 80],
"feb": [110, 90],
})
long = pd.DataFrame({
"store": ["A", "B", "A", "B"],
"month": ["jan", "jan", "feb", "feb"],
"sales": [100, 80, 110, 90],
})
print(wide)
print(long)The wide table has two rows and three columns. Each row is a store, and each month is its own column. The long table has four rows. Each row is one store in one month, and the month names are now values in the month column.
No information is lost in either direction. Only the shape changes.
Why the layout matters
Neither layout is better in general. The right one depends on the task.
| Task | Layout that fits | Reason |
|---|---|---|
| Reading a table by eye | Wide | Rows can be compared side by side. |
| Spreadsheet-style reports | Wide | Each category gets its own column. |
| `groupby` on the category | Long | `groupby` works on column values, and the category must be one. |
| Plotting one line per category | Long | Plotting libraries such as seaborn expect one column for the category and one for the value. |
| Adding a new category | Long | You add rows. A wide table needs a new column. |
The new-category row deserves a closer look. If a mar column appears, every piece of code that lists month columns by name must change. In long layout, March is just another value in month, and the existing code keeps working.
The same question in each layout
Suppose you want total sales per month. In long layout this is one groupby.
print(long.groupby("month")["sales"].sum())In wide layout there is no month column to group by. You would sum the columns directly.
print(wide[["jan", "feb"]].sum())This works, but you must name every month column by hand. For a table with 36 monthly columns, that is a long list. Long layout turns column names into data, so ordinary column operations apply to them.
Recognizing a table that needs reshaping
Look for these signs:
- Column names are values, such as dates, years, or categories, not variable names.
- Several columns hold the same kind of measurement, such as
janandfebboth holding sales. - You want to group, filter, or plot by something that is currently a column name.
The reverse also happens. If a long table has a column whose values you want as side-by-side columns for a report, you need wide layout.
The tools ahead
pandas provides these functions for reshaping:
meltconverts wide to long.pivotconverts long to wide when each store-month pair appears once.pivot_tableconverts long to wide and aggregates duplicates.stack,unstack,wide_to_long, andcrosstabhandle related cases.
The next chapters take them in that order, starting with melt.
Exercise
A table has the columns city, 2022, 2023 and 2024, and each year column holds a population. You want to plot one line per city across years with a library that expects one column for the x-axis and one for the y-axis. Is the table wide or long, and which layout do you need?
Show answer
The table is wide, because the years are column names that act as values. For plotting you need long layout, with columns such as city, year and population, so that year can be the x-axis and population the y-axis.