How to reshape a DataFrame using the index and column values
Overview
The pivot() function in pandas is used to produce a reshaped DataFrame by the given index or column values.
Syntax
pandas.pivot(data, index=None, columns=None, values=None)
Syntax for the pivot() function in Pandas
Parameter value
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 isNone, 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 isNone, the remaining columns will be used.
Return value
The pivot() function returns a reshape of the input DataFrame.
Example
# A code to illustrate the use of pivot() function in Pandas# importing the pandas libraryimport pandas as pd# creating a dataframedf = 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 dataframeprint(df)# reshaping the dataframea = pd.pivot(df, index = "Name", columns="Age", values="Sex")print("\n")# printing the newly reshaped dataframeprint(a)
Explanation
- Line 4: We import the pandas module.
- Lines 7–9: We create a DataFrame and we name it
df. - Line 12: We print the DataFrame object,
df. - Line 15: We reshape the input DataFrame,
df, by using thepivot()function. The result is passed to a variable,a. - Line 18: We print the newly reshaped DataFrame,
a.