← Back to Pandas Course | Chapter 9: Reshaping Data | Lesson 4 of 6

wide_to_long()

wide_to_long unpivots several column groups that share a naming pattern, like score1 and score2.

In this page:

  1. wide_to_long()
Syntax
python
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()

python
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
  1. Forgetting the id column
  2. Suffixes that are not numeric without suffix regex
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.