Pandas pivot() Function Examples
- 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’.
Python3
# values can be an object or a list df.pivot( 'A' , 'B' , '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
# value is a list 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
# importing pandas as pd import pandas as pd # creating a dataframe 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
Python | Pandas.pivot()
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.