Related Articles

Related Articles

How to Create a Pivot table with multiple indexes from an excel sheet using Pandas in Python?
  • Last Updated : 28 Jul, 2020

 The term Pivot Table can be defined as the Pandas function used to create a spreadsheet-style pivot table as a DataFrame. It can be created using the pivot_table() method.

Syntax: pandas.pivot_table(data, index=None)

Parameters:

data : DataFrame
index: column, Grouper, array, or list of the previous

index: It is the feature that allows you to group your data. 



Returns: DataFrame

Note: We can filter the table further by adding the optional parameters. 

Example 1: Link to the CSV File: CSV FILE 
We can have a look at the data by running the following program: 

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# importing pandas as pd 
import pandas as pd
  
# Create the dataframe 
df=pd.read_csv('GeeksForGeeks.csv')
  
# Print the dataframe 
df

chevron_right


Output:

img

We know that the index is the feature that allows us to group our data and specifying multiple columns as the indices in pivot function increases the level of details and grouping the data. 
Keeping a single index in the table: 
 

Python3



filter_none

edit
close

play_arrow

link
brightness_4
code

# importing pandas as pd 
import pandas as pd
  
# Create the dataframe 
df=pd.read_csv('GeeksForGeeks.csv')
  
# Print the resultant table
print(pd.pivot_table(df,index=["Country"]))

chevron_right


Output:

img

As we can see that the grouping is done country wise and the numerical data is printed as the average of all the values with regard to the specified index.
Now, Keeping multiple indices in the table: 
 

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# importing pandas as pd 
import pandas as pd
  
# Create the dataframe 
df=pd.read_csv('GeeksForGeeks.csv')
  
# Print the resultant table
print(pd.pivot_table(df,index=["Country","Salary"]))

chevron_right


Output:

img

Example 2: Link to the CSV File: CSV FILE 
 

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# importing pandas as pd 
import pandas as pd
  
# Create the dataframe 
df=pd.read_csv('GeeksForGeeks_1.csv')
  
# Print the dataframe 
df

chevron_right


Output:

img

Keeping the number of centuries scored by players and their names as indices, we get: 
 

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# importing pandas as pd 
import pandas as pd
  
# Create the dataframe 
df=pd.read_csv('dataset/new_players.csv')
  
# Print the resultant table
print(pd.pivot_table(df,index=["century","name"]))

chevron_right


Output:

img

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :