a.WOL7
a.WOL7

Reputation: 87

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?

Upvotes: 0

Views: 1213

Answers (3)

Just set the regex parameter to False.

This ensures that only exact matches are replaced and not any partial matches.

Upvotes: 1

a.WOL7
a.WOL7

Reputation: 87

Discovered the solution:

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

Upvotes: 1

SM1312
SM1312

Reputation: 588

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)

Upvotes: 1

Related Questions