Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing the first word in a pandas column

Tags:

python

pandas

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!

like image 305
PythonBeginner Avatar asked Dec 06 '25 13:12

PythonBeginner


1 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.

like image 70
Tim Biegeleisen Avatar answered Dec 12 '25 03:12

Tim Biegeleisen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!