Monday, September 1, 2025
HomeLanguagesPython | Pandas.pivot()

Python | Pandas.pivot()

pandas.pivot(index, columns, values) function produces pivot table based on 3 columns of the DataFrame. Uses unique values from index / columns and fills with 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.

Code:




# Create a simple dataframe
  
# importing pandas as pd
import pandas as pd
  
# creating a dataframe
df = pd.DataFrame({'A': ['John', 'Boby', 'Mina'],
      'B': ['Masters', 'Graduate', 'Graduate'],
      'C': [27, 23, 21]})
  
df



 




# values can be an object or a list
df.pivot('A', 'B', 'C')



 




# value is a list
df.pivot(index ='A', columns ='B', values =['C', 'A'])



 
Raise ValueError when there are any index, columns combinations with multiple values.




# 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')


ValueError: Index contains duplicate entries, cannot reshape
Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32251 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6619 POSTS0 COMMENTS
Nicole Veronica
11792 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11841 POSTS0 COMMENTS
Shaida Kate Naidoo
6735 POSTS0 COMMENTS
Ted Musemwa
7016 POSTS0 COMMENTS
Thapelo Manthata
6689 POSTS0 COMMENTS
Umr Jansen
6707 POSTS0 COMMENTS