pandas.pivot(index, columns, values) function produces a pivot table based on 3 columns of the DataFrame. Uses unique values from the index/columns and fills them with values.
Python Pandas.pivot() Syntax
Syntax: pandas.pivot(index, columns, values)
Parameters:
- index[ndarray] : Labels to use to make new frame’s index
- columns[ndarray] : Labels to use to make new frame’s columns
- values[ndarray] : Values to use for populating new frame’s values
Returns: Reshaped DataFrame
Exception: ValueError raised if there are any duplicates.
Creating a Sample DataFrame
Here, we are making a sample DataFrame that we will use in our article throughout.
Python3
import pandas as pd
df = pd.DataFrame({ 'A' : [ 'John' , 'Boby' , 'Mina' ],
'B' : [ 'Masters' , 'Graduate' , 'Graduate' ],
'C' : [ 27 , 23 , 21 ]})
df
|
Output
A B C
0 John Masters 27
1 Boby Graduate 23
2 Mina Graduate 21
Pandas pivot() Function Examples
Below are some examples by which we can pivot a DataFrame using Pandas pivot() function in Python:
- Creating and Pivot a DataFrame
- Creating a Multi-level Pivot Table with Pandas DataFrame
- ValueError in Pivot a DataFrame
Creating and Pivot a DataFrame
In this example, a pandas DataFrame (df
) is pivoted with columns ‘A’ and ‘B’ becoming the new index and columns, respectively, and the values in column ‘C’ populating the cells of the resulting pivot table. The function assumes that each combination of ‘A’ and ‘B’ has a unique corresponding value in ‘C’.
Output
B Graduate Masters
A
Boby 23.0 NaN
John NaN 27.0
Mina 21.0 NaN
Creating a Multi-level Pivot Table with Pandas DataFrame
In this example, the pandas DataFrame (df
) is transformed into a multi-level pivot table, using ‘A’ as the index, ‘B’ as the columns, and extracting values from both columns ‘C’ and ‘A’ to fill the cells. This approach allows for a more detailed representation of the data, incorporating multiple dimensions into the resulting pivot table.
Python3
df.pivot(index = 'A' , columns = 'B' , values = [ 'C' , 'A' ])
|
Output
C A
B Graduate Masters Graduate Masters
A
Boby 23.0 NaN NaN NaN
John NaN 27.0 NaN NaN
Mina 21.0 NaN NaN NaN
ValueError Raised in Pivoting a DataFrame
Raise ValueError when there are any index, columns combinations with multiple values.
Python3
import pandas as pd
df = pd.DataFrame({ 'A' : [ 'John' , 'John' , 'Mina' ],
'B' : [ 'Masters' , 'Masters' , 'Graduate' ],
'C' : [ 27 , 23 , 21 ]})
df.pivot( 'A' , 'B' , 'C' )
|
Output
ValueError: Index contains duplicate entries, cannot reshape
Last Updated :
18 Dec, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...