Replace First word of the column in Pandas

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

  • Replace First word from left of the column in pandas python using split() based on first whitespace.
  • Replace first 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 First word of the column in Pandas 1

 

Replace First word of the column in pandas:

Method1:

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

 

#Use split by first whitespace with n=1 and then select second lists by indexing:

## Method 1:
df['Desc'] =  'Something' + ' '  + df['Description'].str.split(n=1).str[1]
df

Result:

Replace First word of the column in Pandas 2

 

 

Method2:

We will be using regex which will replace the first 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 First 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