简体   繁体   中英

Pandas data frame replace values in column based on condition

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

col
a
b
c
d
e
f
g

and I want to change the values like this:

col
a
b
other
other
other
other
other

I tried like this:

df = df.loc[df.col == ("a" or "b"), "col"] = "other"

but it does not work, I have an error:

AttributeError: 'str' object has no attribute 'loc'

Any advices?

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM