Change some specific values in a column that satisfies the condition in a dataframe

Viewed 25
df[df.CityLocation.str.contains('Delhi',case=False,na=False)].CityLocation= 'New Delhi'

So I want to change any value containing Delhi | delhi | new Delhi | New delhi | DELHI to 'New Delhi' in the column called 'CityLocation'. And I tried the above shown way but it doesn't reflect in dataframe. What am I missing?

2 Answers

use loc:

df.loc[df.CityLocation.str.contains('Delhi',case=False,na=False),"CityLocation"]= 'New Delhi'

try one those options:

# 1/
condition = df['CityLocation'].str.contains('Delhi|Delhi|delhi|new Delhi|New delhi|DELHI',na=False)
df.loc[condition ,"CityLocation"]= 'New Delhi'

# 2/ or with np.where
df['CityLocation'] = np.where(condition, 'New Delhi', df['CityLocation'])

# 3/ or
list_of_substrings = ['Delhi', 'Delhi', 'delhi', 'new Delhi', 'New delhi', 'DELHI']
df['CityLocation'] = df['CityLocation'].map(lambda x: 'New Delhi' if any(i in x for i in list_of_substrings) else x)

# 4/ or
list_of_substrings = ['Delhi', 'Delhi', 'delhi', 'new Delhi', 'New delhi', 'DELHI']
condition = df['CityLocation'].str.contains('|'.join(list_of_substrings),na=False)

df['CityLocation'] = np.where(condition, 'New Delhi', df['CityLocation'])
Related