The pivot()
function in pandas is used to produce a reshaped DataFrame by the given index or column values.
pandas.pivot(data, index=None, columns=None, values=None)
The pivot()
function takes the following parameter values:
data
(required): This is the input DataFrame.index
(optional): This represents the column to be used in creating the index of the new shape. If value is None
, the existing index value is used.columns
(required): This represents the column to be used in creating the column of the new shape. values
(optional): This represents the column to be used for populating the new DataFrame values. If value is None
, the remaining columns will be used.The pivot()
function returns a reshape of the input DataFrame.
# A code to illustrate the use of pivot() function in Pandas # importing the pandas library import pandas as pd # creating a dataframe df = pd.DataFrame({'Name': {0: 'Alek', 1: 'Akim', 2: 'Cynthia'}, 'Age': {0: 20, 1: 30, 2: 50}, 'Sex': {0: "Male", 1: "Male", 2: "Female"}}) # printing the dataframe print(df) # reshaping the dataframe a = pd.pivot(df, index = "Name", columns="Age", values="Sex") print("\n") # printing the newly reshaped dataframe print(a)
df
.df
.df
, by using the pivot()
function. The result is passed to a variable, a
.a
.RELATED TAGS
CONTRIBUTOR
View all Courses