I understand to replace a string in a column would simply be:
df['surf'].replace(to_replace='Grass', value='Turf')
This replaces all the values of 'Grass' with 'Turf' in my column. But I want the opposite of that. I've tried to look up using != or ~, but haven't gotten that to work.
What if I want all the values NOT 'Grass' to be replaced with 'Turf'
Edit: I should add, I can do it with:
df.loc[df['surf'] != 'Grass', 'surf'] = 'Turf'
but was wondering if there was a way with the .replace
you can use a negative lookahead and regex mode to do what you want:
df['surf'] = df['surf'].replace(to_replace=r"^(.(?<!Grass))*?$", value='Turf',regex=True)
(matching everything but the word trick took from How to negate specific word in regex?)
Alternatively, use str.replace, which performs regex-based replacement by default:
df['surf'] = df['surf'].str.replace(r"^(.(?<!Grass))*?$", "Turf")
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