Sub topic 1
Wide versus long: why reshape at all
Prerequisites.
Assume you know basic Python, can create and index pandas DataFrames, and have used groupby with functions such as sum and mean.
Wide versus long: why reshape at all
A wide table stores related measurements in separate columns. A long table stores the measurement name in one column and its value in another.
For example, this wide table has one row per store:
| store | jan | feb |
|---|---|---|
| A | 100 | 110 |
| B | 80 | 90 |
The equivalent long table has one row per store and month. Long data often works better with grouping, filtering, and plotting. Wide data is convenient for reports and human reading.
Turning columns into rows with melt
DataFrame.melt unpivots a wide table. It keeps identifier columns and turns selected measurement columns into two columns: one for the former column names and one for their values.
import pandas as pd
wide = pd.DataFrame({
"store": ["A", "B"],
"jan": [100, 80],
"feb": [110, 90],
})
long = wide.melt(
id_vars="store",
var_name="month",
value_name="sales",
)
print(long)The result has four rows. The store value identifies each observation, while month and sales describe its measurement.
Controlling melt
Use id_vars for columns to preserve on every output row. Use value_vars to choose which columns to stack. If value_vars is omitted, pandas stacks every column not listed in id_vars. var_name and value_name make the generated columns clear.
long = wide.melt(
id_vars="store",
value_vars=["jan", "feb"],
var_name="month",
value_name="sales",
)Turning rows into columns with pivot
DataFrame.pivot reverses this layout when each identifier-column pair has exactly one value.
back = long.pivot(
index="store",
columns="month",
values="sales",
).reset_index()
back.columns.name = None
print(back)Here, store identifies rows, month supplies new columns, and sales supplies their values. If a pair such as (store="A", month="jan") appears more than once, pivot cannot choose a value and raises an error. Use pivot_table with an aggregation function when duplicates need combining.
Exercise
Which argument to melt keeps a column unchanged while other columns become rows?
Show answer
Use idvars, such as idvars="store".