Python | pandas.pivot_table() with examples
In this tutorial, we are going to learn about pandas.pivot_table() in Python with examples. So to do this we need to install pandas library in our machine. In the next section, I’m going to know you how to install it. If you have already installed you can skip this step.
Installation of ‘pandas’
To do this you have to open the command prompt(for Windows users) and terminal (Mac users). Then you need to type the following line:
pip install pandas
Pandas.pivot_table()
To implement pivot_table(),
At first, we need to create a dataset using the pandas library. To do this we have just to write the following code:
import pandas data_frame = pandas.DataFrame({'Name': ['Milan', 'Virat', 'Sanaya', 'Alina', 'Zakir'], 'Gender': ['Male', 'Male', 'Female', 'Female', 'Male'], 'Age': [25, 32, 19, 22, 30]}) data_frame
Here we’ve created a data frame and check if the data frame is successfully created or not.
Next, we need to use pandas.pivot_table() to show the data set as in table form. As the arguments of this function, we just need to put the dataset and column names of the function. To do this we need to write this code:
table = pandas.pivot_table(data_frame, index =['Name', 'Gender']) table
My whole code is here:
import pandas data_frame = pandas.DataFrame({'Name': ['Milan', 'Virat', 'Sanaya', 'Alina', 'Zakir'], 'Gender': ['Male', 'Male', 'Female', 'Female', 'Male'], 'Age': [25, 32, 19, 22, 30]}) data_frame table = pandas.pivot_table(data_frame, index =['Name', 'Gender']) table
And you are going to see an output similar to this:
https://drive.google.com/open?id=1N6nCgMkxI1bzFPEgLC0oUVr957V4KZUm
Leave a Reply