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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With