0

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?

3 Answers 3

1

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)
Sign up to request clarification or add additional context in comments.

Comments

1

Discovered the solution:

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

Comments

1

Just set the regex parameter to False.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.