We change data from long to wide format to make it easier to compare values side by side. This helps us see patterns and differences clearly.
Long to wide format conversion in Pandas
df_wide = df.pivot(index='row_id', columns='column_id', values='value_column')
index: The column to keep as rows in the wide table.
columns: The column whose unique values become new columns.
values: The column whose values fill the new table's cells.
df_wide = df.pivot(index='Date', columns='Product', values='Sales')
df_wide = df.pivot(index='Person', columns='Question', values='Answer')
This example shows survey answers from two people. We use pivot to make each question a column, so each person's answers are in one row.
import pandas as pd data = {'Person': ['Alice', 'Alice', 'Bob', 'Bob'], 'Question': ['Q1', 'Q2', 'Q1', 'Q2'], 'Answer': [5, 3, 4, 2]} df = pd.DataFrame(data) # Convert from long to wide format wide_df = df.pivot(index='Person', columns='Question', values='Answer') print(wide_df)
If your data has duplicate entries for the same index and column, pivot will give an error. Use pivot_table with an aggregation function instead.
The result's columns become a special type called MultiIndex if you pivot multiple columns; you can flatten it if needed.
Long to wide format helps compare data side by side by turning row values into columns.
Use pivot with index, columns, and values to reshape data.
Make sure your data has unique pairs of index and columns to avoid errors.