Replace Last word of the column in Pandas

In This Section we will be focusing on how to replace last word of the character column in pandas in two ways.

  • Replace last word from right of the column in pandas python using rsplit() based on first whitespace.
  • Replace last word of the column in pandas python using regular expression.

Let’s Look at these cases with Example,

 

Create Dataframe:

## create dataframe

import pandas as pd
d = {'Day' : ['day1','day2','day3','day4'], 'Description' : ['First day of the year', 'Second day of the year', 'Third day of the year', 'FOURTH day of the YEAR']}
df=pd.DataFrame(d)
df

Result dataframe is

Replace Last word of the column in Pandas 1

 

 

 

Replace last word of the column in pandas:

Method1:

We will be using rsplit() method and will be splitting the last whitespace with n=1 and then select the first list by indexing and add ‘something’ to the end , which will replace the last word of the column as shown below.

#Use rsplit by last whitespace with n=1 and then select first lists by indexing and add 'Something':
## Method 1:
df['Desc'] =  df['Description'].str.rsplit(n=1).str[0] + ' ' + 'Something'
df

Result:

Replace last word of the column in Pandas 2

 

Method2:

We will be using regex which will replace the last word of the column with word ‘something’ as shown below.

#Method 2:Using Regex

df['Desc'] = df['Description'].str.replace(r'\w+$', 'Something')
df

Result:

Replace last word of the column in Pandas 2

 

                                                                                                         

 

Author

  • Sridhar Venkatachalam

    With close to 10 years on Experience in data science and machine learning Have extensively worked on programming languages like R, Python (Pandas), SAS, Pyspark.

    View all posts