Sample DataFrame context
A wide spreadsheet exported from a reporting system.
Syntax or pattern
pd.wide_to_long(df, stubnames="sales", i="product", j="month")5 practical examples
Unpivot monthly columns
Turn Jan, Feb and Mar columns into rows.
long = df.melt(id_vars="product", var_name="month", value_name="sales")The data becomes easier to group, chart and filter.
Create a revenue matrix
Place regions as rows and months as columns.
matrix = pd.pivot_table(sales, values="revenue", index="region", columns="month", aggfunc="sum", fill_value=0)The result is an Excel-like summary table.
Reset the index after reshaping
Return a grouped or pivoted output to normal columns.
output = matrix.reset_index()The output can be exported or merged with other tables.
Split list values into rows
Use explode for tags or product lists.
expanded = df.explode("tags")Each tag gets its own row for filtering or counting.
Validate reshaped totals
Compare totals before and after reshaping.
df["sales"].sum(), long["sales"].sum()Matching totals help confirm the reshape did not lose values.
Common mistakes to avoid
- Changing the original DataFrame before checking the result.
- Forgetting to inspect row counts before and after the operation.
- Using a pattern without confirming column names and data types.
FAQ
What is the main use of Wide to Long Examples?
Convert spreadsheets with repeated period columns into tidy data.
Should I use this in a notebook or a script?
Both work. Use a notebook while exploring the data, then move the final workflow into a repeatable script when it is stable.
How do I avoid breaking my source data?
Create a copy of the DataFrame before transforming it and check row counts, missing values and sample rows after each important step.