Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and the data. A certain operation can be performed on DataFrames.
Many times, for a better understanding of datasets or to analyze the data according to our compatibility, we need to reorder or reshape the given DataFrame according to index and column values. DataFrame.pivot() helps us to achieve this task.
pandas.DataFrame.pivot() Method
This method is used to reshape the given DataFrame according to index and column values. It is used when we have multiple items in a column, we can reshape the DataFrame in such a way that all the multiple values fall under one single index or row, similarly, we can convert these multiple values as columns. Suppose we have a column name ‘column’ having 3 repeating values (let p,q,r), if we pivot the DataFrame and define the columns = 'column', then the resulted pivot table will consist of 3 new columns named P, Q, R.
Syntax:
df.pivot(index='col_name', columns='col_name', values='col_name')
Parameter(s):
- It takes the index as a parameter which is a column name and will be converted into a new row for the new DataFrame.
- It takes columns as a parameter which is a column name and will be converted into a new column for the new DataFrame.
- Also, it takes values as a parameter which is a column name and its values will be the final values of the new columns of the new DataFrame.
To work with pandas, we need to import pandas package first, below is the syntax:
import pandas as pd
Let us understand with the help of an example:
Output:
We have created a DataFrame, now we will use the pivot() method to pivot this given DataFrame.
Output:

need an explanation for this answer? contact us directly to get an explanation for this answer