Python | Pandas dataframe.add_prefix ()

Python Methods and Functions

Dataframe.add_prefix() can be used with both series and data frames.

  • For series, row labels are prefixed .
  • For DataFrame, column labels are prefixed.
  Syntax:  DataFrame.add_prefix (prefix)  Parameters:   prefix:  string  Returns:  with_prefix: type of caller 

To link to the CSV file used in the code, click here

Example # 1: prefix col_ in each col_ in col_

# import pandas as pd

import pandas as pd

 
 # Create data frame from CSV file

df = pd.read_csv ( " nba.csv " )

 
# Print the first 10 lines
# dataframe for rendering

df [: 10 ]

# Using the add_prefix () function
# add & # 39; col _ & # 39; to each column label

df = df .add_prefix ( 'col_' )

  
# Print the data frame
df 

Output:

Example # 2: Using add_prefix () with series in pandas

add_prefix () changes row index labels in case of a series.

# import pandas as pd

import pandas as pd

 
#Cos giving the series

df = pd.Series ([ 1 , 2 , 3 , 4 , 5 , 10 , 11 , 21 , 4 ])

 
# This will be the prefix & # 39; Row _ & # 39; in
# each row of the series

df = df.add_prefix ( ' Row_' )

 
# Print series
df

Output:





Get Solution for free from DataCamp guru