0
0
Pandasdata~5 mins

Long to wide format conversion in Pandas

Choose your learning style9 modes available
Introduction

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.

You have survey data where each row is one answer, and you want each person's answers in one row.
You track sales by date and product, and want each product's sales as separate columns for each date.
You collect temperature readings at different times and want each time as a separate column.
You want to create a summary table where categories become columns for easier analysis.
Syntax
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.

Examples
This turns sales data from long to wide, showing each product's sales per date in separate columns.
Pandas
df_wide = df.pivot(index='Date', columns='Product', values='Sales')
This arranges survey answers so each person has one row with answers to all questions as columns.
Pandas
df_wide = df.pivot(index='Person', columns='Question', values='Answer')
Sample Program

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.

Pandas
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)
OutputSuccess
Important Notes

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.

Summary

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.