简体   繁体   English

Pandas 数据框根据条件替换列中的值

[英]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.您的代码的问题是, df在此过程中正在更改为类型字符串。

There exists a pandas function for this usecase, named pd.where() .这个用例存在一个 pandas function ,名为pd.where()

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

Similar result avoiding where() :避免where()类似结果:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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