Sub topic 12
Reshaping prefixed column groups with wide_to_long
This chapter assumes you know melt, the meaning of id_vars, and how to reset an index. You should also be comfortable with a regular expression such as \w+.
The problem melt does not solve cleanly
Some wide tables hold several columns that share a prefix, such as score_math and score_art. The prefix names the measurement. The suffix names a category, here the subject.
melt can stack these columns, but the old column names end up as single strings like score_math. You would then need to split each string yourself. pd.wide_to_long does the split and the stacking in one call.
Basic use
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 60The arguments work like this:
| Argument | Meaning |
|---|---|
| `stubnames` | The prefix, or a list of prefixes, that start the columns to stack |
| `i` | Column or columns that identify one input row. Their values must be unique |
| `j` | Name of the new column that receives the suffixes |
| `sep` | Text between the prefix and the suffix |
| `suffix` | Regular expression that the suffix must match |
The result has a MultiIndex
wide_to_long returns a DataFrame indexed by i and j together. That is why the example calls reset_index(). Without it, id and subject stay in the index, and code that selects them as ordinary columns fails.
Several prefixes at once
Pass a list to stubnames to reshape several column groups together. Each prefix becomes its own value column, and the rows stay aligned by suffix.
import pandas as pd
df = pd.DataFrame({
"id": [1, 2],
"x_2023": [5, 6],
"x_2024": [7, 8],
"y_2023": [1, 2],
"y_2024": [3, 4],
})
long = pd.wide_to_long(
df, stubnames=["x", "y"], i="id", j="year", sep="_"
).reset_index()
print(long)This yields four rows with the columns id, year, x and y. Doing the same with melt would take two calls and a merge.
Common errors
- An empty result for text suffixes. The default
suffixis\d+, which matches digits only. With suffixes likemathandart, no columns match and you get no value data. Setsuffix=r"\w+"or another pattern that fits. - Duplicate values in
i. If theicolumns do not identify rows uniquely, pandas raises aValueError. Add more columns toi, or create a row identifier first withdf.reset_index(). - A wrong
sep. If the columns arescore1andscore2with no separator, usesep="". If you leavesep="_"in place, the names will not match. - Numeric suffixes become integers. When the default digit suffix is used,
jis converted to a number. A pattern such as\w+leaves the suffixes as strings.
When to choose it
Use wide_to_long when the column names follow a consistent prefix + sep + suffix pattern, especially with more than one prefix. Use melt when the columns have no shared structure, or when you only need the old names stacked into one column.
Exercise
A DataFrame has the columns "id", "tempmon" and "temptue". You call pd.widetolong(df, stubnames="temp", i="id", j="day", sep="_") and the result has no data rows. What is wrong and how do you fix it?
Show answer
The default suffix pattern is \d+, which matches only digits, so "mon" and "tue" do not match. Add suffix=r"\w+" to the call. Then call reset_index() if you want id and day as ordinary columns.
Exercise
Why does widetolong require the i columns to identify each input row uniquely?
Show answer
The function stacks the suffix groups and then indexes the result by i and j. If two input rows shared the same i value, the output would contain duplicate (i, j) pairs and rows from different inputs could not be told apart, so pandas raises a ValueError.