How to prefix the labels of a series object in pandas

Overview

The add_prefix() function in pandas is used to prefix the rows of a Series object.

A Series object is a one-dimensional data structure used to hold integers, strings, and other python objects.

Syntax

The add_prefix() function takes the syntax shown below:

DataFrame.add_prefix(str)
Syntax for the add_prefix() function

Parameter value

The add_prefix() function takes a single required parameter value, str, representing the string to be prefixed or added before each label.

Return value

The add_prefix() function returns a new dataframe with prefixed columns.

Example

# A code to illustrate the add_prefix() function in Pandas
# imporing the pandas library
import pandas as pd
# creating a dataframe
df = pd.Series([10, 20, 30, 40, 50])
print(df)
# adding prefixes to the columns of the dataframe
print(df.add_prefix("row_"))

Explanation

  • Line 4: We import the pandas library.
  • Line 7: We create a dataframe called df.
  • Line 9: We print the df.
  • Line 12: We add the prefix row_ to the row labels of the df. We print the result to the console.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources