how to Convert Pandas Pivot Table to DataFrame

To convert a Pandas Pivot Table to a DataFrame, you can use the Pandas “to_frame()” function. This will take the values in the pivot table and convert them into a DataFrame with labeled columns. You can also use the “reset_index()” function to make the columns of the DataFrame more meaningful and easier to work with. Additionally, you can use the “reset_index(drop=True)” function to get rid of the index column that is created by the reset_index() function.


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 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

x