'Pandas data frame replace values in column based on condition

I have a column in data frame like this (an simplify example):

col    col2
a       1
b       2
c       5
d       12
e       1
f       4
g       1

and I want to change the values like this:

col    col2
a       1
b       2
other   5
other   12
other   1
other   4
other   1

I tried like this:

df = df.where(df["col"].isin(["a", "b"]), "Other")

but I get:

col    col2
a       1
b       2
other   other
other   other
other   other
other   other
other   other

Any advices?



Solution 1:[1]

The problem with your code is, that df is changing to type string during the process.

There exists a pandas function for this usecase, named pd.where().

df = df.where(df['col'].isin(['a', 'b']),'other')

Similar result avoiding where():

df[~df['col'].isin(['a', 'b'])] = 'other'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jon Clements