![]() |
VOOZH | about |
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.
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.
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 21Below are some examples by which we can pivot a DataFrame using Pandas pivot() function in Python:
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 NaNIn 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 NaNRaise ValueError when there are any index, columns combinations with multiple values.
Output
ValueError: Index contains duplicate entries, cannot reshape