wide_to_long()
wide_to_long unpivots several column groups that share a naming pattern, like score1 and score2.
In this page:
Syntax
long_df = pd.wide_to_long(df, stubnames="stub", i="id_column", j="suffix_column")
wide_to_long()
pd.wide_to_long(df, stubnames, i, j) collects columns starting with each stub name and ending in a suffix into rows. It is useful for repeated measurements such as year-by-year columns. i identifies the row and j names the extracted suffix.
Note:
Set sep="_" if suffixes are separated by an underscore.
Example: wide_to_long()
import pandas as pd
df = pd.DataFrame({"id": [1, 2], "score_2023": [10, 20], "score_2024": [15, 25]})
print(pd.wide_to_long(df, stubnames="score", i="id", j="year", sep="_"))
# Output:
# score
# id year
# 1 2023 10
# 2 2023 20
# 1 2024 15
# 2 2024 25
Related Topics
Common Mistakes
- Forgetting the id column
- Suffixes that are not numeric without suffix regex
- Confusing it with melt
Chapter Summary
- Handles column groups with common stubs
- i identifies rows
- j names the suffix column
- sep sets the separator
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: