Home » How to Convert Pandas Pivot Table to DataFrame

How to Convert Pandas Pivot Table to DataFrame

by Erma Khan

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

Related Posts