Home > Software engineering >  Pandas: Using .replace in a Dataframe but only replace on an exact match
Pandas: Using .replace in a Dataframe but only replace on an exact match

Time:04-13

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?

CodePudding user response:

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)

CodePudding user response:

Discovered the solution:

df['Brand'] = df['Brand'].str.replace(r'(?i)stack\b', r'stackoverflow')
  • Related