Zenvega
Zenvega

Reputation: 2054

pandas replace string value if not in a list

I have a pandas dataframe

     city
0 los angeles
1 houston
2 new york
:
:
100 boston
:
:

How can I replace all the city names to other which are not in in the following list?

los angeles
saint petersburg
honolulu
Denverver
las vegas
saint louis
phoenix
houston
atlanta
philadelphia
orlando
chicago
san francisco
kailua kona

Upvotes: 0

Views: 31

Answers (1)

anon01
anon01

Reputation: 11171

You can do something like this:

cities = ['los angeles',
 'saint petersburg',
 'honolulu',
 'Denverver',
 'las vegas',
 'saint louis',
 'phoenix',
 'houston',
 'atlanta',
 'philadelphia',
 'orlando',
 'chicago',
 'san francisco',
 'kailua kona']

df.loc[~df["city"].isin(cities), "city"] = "other"

Upvotes: 1

Related Questions