Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

pandas
data science
communitycreator

How to reshape a DataFrame using the index and column values

Alek Akim

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 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.

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 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)
Implementing the pivot()

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 the pivot() function. The result is passed to a variable, a.
  • Line 18: We print the newly reshaped DataFrame, a.

RELATED TAGS

pandas
data science
communitycreator
RELATED COURSES

View all Courses

Keep Exploring