Sub topic 12
Reshaping prefixed column groups with wide_to_long
This chapter assumes you know melt (including id_vars, var_name and value_name), basic regular expressions, and how to read a MultiIndex on a DataFrame. Spreadsheets and survey exports often hold several measurements per row, with column names such as score_math, score_art, hours_math and hours_art. pd.wide_to_long unpivots these groups in one call.
The problem melt does not solve cleanly
melt handles one family of columns well. Suppose a table has two families, one for scores and one for hours, each split by subject. A single melt call gives you one value column that mixes both families. To build a proper long table you would need to:
- Melt the score columns and melt the hours columns separately.
- Split each melted column name into a measurement part and a subject part.
- Merge the two results on
idandsubject.
wide_to_long does all three steps. It relies on a naming convention: each column name is a stub (the measurement name), then a separator, then a suffix (the value that identifies the group member).
| Column name | Stub | Separator | Suffix |
|---|---|---|---|
| `score_math` | `score` | `_` | `math` |
| `score_art` | `score` | `_` | `art` |
| `gdp_2021` | `gdp` | `_` | `2021` |
The function produces one output column per stub. The suffixes become values in a new column that you name with j.
A first example
This is the example from the plan. It reshapes one stub with a text suffix.
import pandas as pd
scores = pd.DataFrame({
"id": [1, 2],
"score_math": [90, 80],
"score_art": [70, 60],
})
tidy = pd.wide_to_long(
scores, stubnames="score", i="id", j="subject", sep="_", suffix=r"\w+"
).reset_index()
print(tidy)The output has four rows:
id subject score
0 1 math 90
1 2 math 80
2 1 art 70
3 2 art 60Each argument does one job:
stubnamesis a string or list of strings naming the prefixes to collect.iis the column or list of columns that identifies a row in the wide table. These become part of the index.jis the name of the new column that receives the suffixes.sepis the text between the stub and the suffix. The default is the empty string.suffixis a regular expression describing which suffixes are allowed. The default is\d+, digits only.
The function returns a DataFrame indexed by i and j. That is why the example calls reset_index(), which turns id and subject back into ordinary columns. This is the same cleanup step you use after pivot.
Rows come out grouped by suffix, in the order the columns appear in the input. All the math rows come first, then all the art rows. Sort with sort_values if you need a different order.
Why the default suffix often returns nothing
The most common mistake is leaving out suffix. The default pattern is \d+, so a column such as score_math does not match. In that case you usually get an empty result, not an error.
The whole column name must match stub + sep + suffix, not just the start of it. To work out what to pass, write the pattern for your names:
| Column names | Settings that work |
|---|---|
| `score1`, `score2` | defaults (`sep=""`, `suffix=r"\d+"`) |
| `gdp_2020`, `gdp_2021` | `sep="_"` |
| `score_math`, `score_art` | `sep="_"`, `suffix=r"\w+"` |
| `q1.a`, `q2.a` (stub is the part after the dot) | needs renaming first, see below |
wide_to_long requires the stub to come first. If your names put the identifying part first, as in math_score, rename the columns before calling it. A list comprehension over df.columns that swaps the parts works well.
Several stubs at once
The real benefit shows when you pass a list of stubs. Each stub becomes its own column, and rows line up on the shared suffix.
import pandas as pd
df = pd.DataFrame({
"country": ["A", "B"],
"pop_2020": [10, 20],
"pop_2021": [11, 21],
"gdp_2020": [100, 200],
"gdp_2021": [110, 210],
})
long = pd.wide_to_long(
df, stubnames=["pop", "gdp"], i="country", j="year", sep="_"
).reset_index()
print(long)
print(long.dtypes)The output is:
country year pop gdp
0 A 2020 10 100
1 B 2020 20 200
2 A 2021 11 110
3 B 2021 21 210The default suffix works here because the years are digits. The year column has an integer dtype. When every suffix is made of digits, wide_to_long converts the new j column to numbers. With a text suffix such as math, the column stays as strings.
The output has one row per country and year. Each row carries both measurements, so you can compute a ratio without a merge:
long["gdp_per_person"] = long["gdp"] / long["pop"]Columns that match no stub
Any column that is not in i and does not match a stub is kept and repeated on every output row for the same i value. Suppose the scores table also has a name column. It appears in the result as an ordinary column, so you do not need to list it in i.
This repetition is correct only when the extra column has one value per i. If name could differ between rows that share an id, the repeated value would be wrong. In that case, include name in i or drop it first.
When i does not identify rows
i must be unique in the wide table. If two input rows share the same i value, the function cannot tell which input row each output row came from. It raises a ValueError stating that the id variables need to uniquely identify each row.
import pandas as pd
dup = pd.DataFrame({
"id": [1, 1],
"score_math": [90, 85],
"score_art": [70, 65],
})
try:
pd.wide_to_long(dup, "score", i="id", j="subject", sep="_", suffix=r"\w+")
except ValueError as err:
print("failed:", type(err).__name__)There are two fixes:
- Add more columns to
iuntil the combination is unique, for examplei=["id", "visit"]. - Create a unique row key first with
df.reset_index().rename(columns={"index": "row"}), then usei="row".
This is a different failure from pivot on duplicate keys, but the cause is the same. A reshape needs a unique key per row to know where each value belongs.
Choosing between wide_to_long and melt
Both functions turn columns into rows, but they suit different shapes of data.
| Situation | Better tool |
|---|---|
| One family of columns, arbitrary names | `melt` |
| Several families that share the same suffixes | `wide_to_long` |
| Column names do not follow stub, separator, suffix | `melt`, or rename first |
| You want the suffix as its own column and the stubs as separate value columns | `wide_to_long` |
| Only some columns should be reshaped, chosen by list | `melt` with `value_vars` |
An alternative for a single family is melt followed by str.split on the variable column. This works when the names are irregular, but it gives you one value column. With two or more families you would then need a pivot to get stub columns back. wide_to_long is shorter for that case.
Going back to wide
wide_to_long has no dedicated inverse. To return to the wide layout, use pivot on the long result and flatten the columns, as you did in the chapters on MultiIndex columns. With several stub columns, values=["pop", "gdp"] produces two-level column labels:
wide_again = long.pivot(index="country", columns="year", values=["pop", "gdp"])
wide_again.columns = [f"{stub}_{year}" for stub, year in wide_again.columns]
wide_again = wide_again.reset_index()
print(wide_again)Because the flattening reuses the original stub_suffix naming, the result has the same column names as the input, in the order pop_2020, pop_2021, gdp_2020, gdp_2021.
Checklist for using wide_to_long
- List the column names and write down the stub, separator and suffix of each one.
- Check that the stub comes first in every name.
- Set
sepandsuffixso that the whole name matches. Remember that the default suffix is digits only. - Choose
iso that it identifies each wide row uniquely. - Call
reset_index()if you wantiandjas ordinary columns. - Check the result: the row count should equal the number of input rows times the number of distinct suffixes.
Exercise
A DataFrame has the columns id, temp_am, temp_pm, humid_am and humid_pm. Write the wide_to_long call that returns one row per id and time of day, with temp and humid as columns and the time of day in a column named period. Then say why the call fails to return rows if you leave out the suffix argument.
Show answer
Use pd.wide_to_long(df, stubnames=["temp", "humid"], i="id", j="period", sep="_", suffix=r"\w+").reset_index(). The result has two rows per id, one for am and one for pm. Without suffix, the default pattern is \d+ (digits only), so am and pm never match, and no columns are found for either stub.
Exercise
A wide table has two rows with id equal to 7, and you call wide_to_long with i="id". What happens, and how do you fix it without dropping data?
Show answer
It raises a ValueError because id does not identify each row uniquely. Fix it by adding another column that distinguishes the rows to i (for example i=["id", "visit"]), or by creating a unique row key with reset_index() and using that as i.