'Pandas: Using .replace in a Dataframe but only replace on an exact match
In my Dataframe I'm using the following to replace 'stack' in the Brand column with 'stackoverflow'
df['Brand'] = df['Brand'].replace('stack', 'stackoverflow', regex=True)
Problem is if stackoverflow exists in the column, I end up with stackoverflowoverflow.
Is there a way to replace stack when the field in the column is only equal to stack and not effect other rows in the column that may contain the keyword stack?
Solution 1:[1]
Discovered the solution:
df['Brand'] = df['Brand'].str.replace(r'(?i)stack\b', r'stackoverflow')
Solution 2:[2]
This should do n would be useful if you have multiple replacements to do:
replace_dict = {'stack' : 'stackoverflow'}
replacement = {rf'\b{k}\b': v for k, v in replace_dict.items()}
df['Brand'] = df['Brand'].replace(replacement, regex=True)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | a.WOL7 |
| Solution 2 | SM1312 |
