17.8 C
London
Sunday, June 22, 2025
HomePandas in PythonGeneral Functions in PythonPandas: How to Reshape DataFrame from Long to Wide

Pandas: How to Reshape DataFrame from Long to Wide

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

You can use the following basic syntax to convert a pandas DataFrame from a long format to a wide format:

df = pd.pivot(df, index='col1', columns='col2', values='col3')

In this scenario, col1 will become the index, col2 will become the columns, and col3 will be used as the values inside the DataFrame.

The following example shows how to use this syntax in practice.

Example: Reshape Pandas DataFrame from Long to Wide

Suppose we have the following pandas DataFrame in a long format:

import pandas as pd

#create DataFrame in long format
df = pd.DataFrame({'team': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],
                   'player': [1, 2, 3, 4, 1, 2, 3, 4],
                   'points': [11, 8, 10, 6, 12, 5, 9, 4]})

#view DataFrame
df

	team	player	points
0	A	1	11
1	A	2	8
2	A	3	10
3	A	4	6
4	B	1	12
5	B	2	5
6	B	3	9
7	B	4	4

We can use the following syntax to reshape this DataFrame from a long format to a wide format:

#reshape DataFrame from long format to wide format
df = pd.pivot(df, index='team', columns='player', values='points')

#view updated DataFrame
df

player	1	2	3	4
team				
A	11	8	10	6
B	12	5	9	4

The DataFrame is now in a wide format.

We used ‘team’ as the index column, ‘player’ as the columns, and ‘points’ as the values inside of the DataFrame.

Note that we could instead use ‘player’ as the index column and ‘team’ as the columns if we’d like:

#reshape DataFrame from long format to wide format
df = pd.pivot(df, index='player', columns='team', values='points')

#view updated DataFrame
df

team	A	B
player		
1	11	12
2	8	5
3	10	9
4	6	4

This DataFrame is also in a wide format.

Note: You can find the complete documentation for the pandas pivot() function here.

Additional Resources

The following tutorials explain how to perform other common operations in Python:

Pandas: How to Reshape DataFrame from Wide to Long
How to Add Rows to a Pandas DataFrame
How to Add Columns to a Pandas DataFrame
How to Count Occurrences of Specific Values in Pandas DataFrame

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories