In This Section we will be focusing on how to remove suffix from the column name in pandas python. There are multiple ways to do it, We will also remove suffix from column name in pandas using functions like rstrip(), rename() and replace() function. let’s look at each of these cases in pandas with an example for each.
- Remove suffix from column name in pandas using rstrip() function
- Remove suffix from column name in pandas using rstrip() and rename() function
- Remove Suffix from the column name in pandas
Create Dataframe:
#Create a DataFrame import pandas as pd import numpy as np d = { 'Name_x':['Alisa','Bobby','Cathrine','Jodha','Raghu','Ram'], 'Maths_x':[76,73,83,93,89,94], 'Science':[85,41,55,75,81,97], 'Geography':[78,65,55,88,87,98]} df = pd.DataFrame(d,columns=['Name_x','Maths_x','Science','Geography']) df
The Resultant dataframe is
Remove suffix from column name in pandas using rstrip() function:
We will be using rstrip() function. Within rstrip() we will be passing the string which will be stripped from right .i.e. suffix is stripped or removed in the column name. so the resultant column name will not have suffix as shown below
#### remove suffix from column name in pandas using rstrip() function df.columns = df.columns.str.rstrip('_x') df
The Resultant dataframe with suffix “_x” removed is
Remove suffix from column name in pandas using rstrip() and rename() function:
We will be using rstrip() function along with rename() function. Within rstrip() we will be passing the string which will be stripped from right .i.e. suffix is stripped or removed in the column name. This is done for each column using lambda and the column name will be renamed using rename() function as shown below
#### remove suffix from column name in pandas using rstrip() and rename() function df=df.rename(columns = lambda x: x.rstrip('_x')) df
The Resultant dataframe with suffix “_x” removed and renamed is
Remove suffix from column name in pandas using replace() function:
We will be using replace() function to remove suffix from column name. This is the most easiest method we will simple replacing the suffix value with empty value through replace() function for all the columns in the dataframe. So all the column name with desired suffix will be replaced using replace() function as shown below
### Remove Suffix from the column name in pandas df.columns = [col.replace('_x', '') for col in df.columns] df
The Resultant dataframe with suffix “_x” replaced with “” is