19.4 C
London
Friday, June 20, 2025
HomePandas in PythonGeneral Functions in PythonHow to Convert Pandas Pivot Table to DataFrame

How to Convert Pandas Pivot Table to DataFrame

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 syntax to convert a pandas pivot table to a pandas DataFrame:

df = pivot_name.reset_index()

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

Example: Convert Pivot Table to DataFrame

Suppose we have the following pandas DataFrame:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'team': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],
                   'position': ['G', 'G', 'F', 'F', 'G', 'G', 'F', 'F'],
                   'points': [11, 8, 10, 6, 6, 5, 9, 12]})

#view DataFrame
df

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

We can use the following code to create a pivot table that displays the mean points scored by team and position:

#create pivot table
df_pivot = pd.pivot_table(df, values='points', index='team', columns='position')

#view pivot table
df_pivot

position	F	  G
team		
A	      8.0	9.5
B	     10.5	5.5

We can then use the reset_index() function to convert this pivot table to a pandas DataFrame:

#convert pivot table to DataFrame
df2 = df_pivot.reset_index()

#view DataFrame
df2

	team	F	G
0	A	8.0	9.5
1	B	10.5	5.5

The result is a pandas DataFrame with two rows and three columns.

We can also use the following syntax to rename the columns of the DataFrame:

#convert pivot table to DataFrame
df2.columns = ['team', 'Forward_Pts', 'Guard_Pts']

#view updated DataFrame
df2

        team	Forward_Pts  Guard_Pts
0	A	8.0	     9.5
1	B	10.5	     5.5

Additional Resources

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

Pandas: How to Reshape DataFrame from Long to Wide
Pandas: How to Reshape DataFrame from Wide to Long
Pandas: How to Group and Aggregate by Multiple Columns

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