Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python to_replace string NOT equal to a value?

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

like image 687
chitown88 Avatar asked Jun 24 '26 12:06

chitown88


1 Answers

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")
like image 72
Jean-François Fabre Avatar answered Jun 27 '26 01:06

Jean-François Fabre