0
0
Pandasdata~5 mins

Why reshaping data matters in Pandas

Choose your learning style9 modes available
Introduction

Reshaping data helps you change how data is organized so it is easier to understand and analyze.

You want to turn columns into rows to compare values easily.
You need to combine multiple columns into one for simpler analysis.
You want to spread one column into many to see details clearly.
You have messy data and want to clean it into a neat table.
You want to prepare data for charts or machine learning.
Syntax
Pandas
df.melt(id_vars=None, value_vars=None, var_name=None, value_name='value')
df.pivot(index=None, columns=None, values=None)
df.stack()
df.unstack()

melt() turns columns into rows.

pivot() turns rows into columns.

Examples
This changes the Math and English columns into rows, keeping Name fixed.
Pandas
df.melt(id_vars=['Name'], value_vars=['Math', 'English'])
This turns the Subject rows into columns with their Scores.
Pandas
df.pivot(index='Name', columns='Subject', values='Score')
This stacks columns into a single column, making data longer.
Pandas
df.stack()
This unstacks a level of row index into columns, making data wider.
Pandas
df.unstack()
Sample Program

This code shows how to reshape data from wide to long format using melt(), then back to wide format using pivot(). This helps you see the same data in different ways for easier analysis.

Pandas
import pandas as pd

# Create a simple data table
data = {'Name': ['Alice', 'Bob'], 'Math': [90, 80], 'English': [85, 88]}
df = pd.DataFrame(data)

# Show original data
print('Original DataFrame:')
print(df)

# Reshape data from wide to long format
melted = df.melt(id_vars=['Name'], value_vars=['Math', 'English'], var_name='Subject', value_name='Score')
print('\nMelted DataFrame:')
print(melted)

# Reshape back from long to wide format
pivoted = melted.pivot(index='Name', columns='Subject', values='Score').reset_index()
print('\nPivoted DataFrame:')
print(pivoted)
OutputSuccess
Important Notes

Reshaping does not change your data values, only how they are arranged.

Use reshaping to match the format needed for your analysis or visualization.

Summary

Reshaping helps organize data for easier understanding.

Use melt() to make data longer and pivot() to make it wider.

It is a key step before analysis or making charts.