Replacing the first word in a pandas column

Viewed 248

I am trying to replace the first word in a column (pandas DF) with "MS". I have read multiple sources online and cannot find what I am looking for.

As the first word can vary throughout I was thinking of using a positional argument rather than the regular one below:

df['columnName'].replace(['old value'],'new value')

I have a snippet code to isolate the first word in the column but I'm not sure how to go about implementing the .replace method

df['hardware']= df['hardware'].str.split(' ').str[0]

Sample df

Hardware
Micro Software
sample Software
MS Screen
Xyx Screen

Desired output

Hardware
MS Software
MS Software
MS Screen
MS Screen

Many thanks!

2 Answers

Use a regex replacement:

df['columnName'] = df['columnName'].str.replace(r'^\w+', 'MS')

The regex pattern ^\w+ will match the first word in the column.

Have you thought about df.iloc method?

df.iloc[0, df.columns.get_loc('hardware')] = 'new value'
Related