VOOZH about

URL: https://www.geeksforgeeks.org/python/python-pandas-pivot/

⇱ Python | Pandas.pivot() - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python | Pandas.pivot()

Last Updated : 11 Jul, 2025

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:

  1. index[ndarray] : Labels to use to make new frame’s index
  2. columns[ndarray] : Labels to use to make new frame’s columns
  3. 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.

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.

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.

Output

ValueError: Index contains duplicate entries, cannot reshape
Comment