python - 如何在 np.where 中使用两个条件

标签 python numpy

data['BUILDING CLASS CATEGORY'] = np.where(data['BUILDING CLASS 
CATEGORY']!='01 ONE FAMILY DWELLINGS' or '02 TWO FAMILY 
DWELLINGS ', 'OTHERS' , data['BUILDING CLASS CATEGORY'])

都不是

data['BUILDING CLASS CATEGORY'] = np.where(data['BUILDING CLASS 
CATEGORY']!='01 ONE FAMILY DWELLINGS' or data['BUILDING 
CLASS CATEGORY']!='02 TWO FAMILY DWELLINGS', 'OTHERS' , 
data['BUILDING CLASS CATEGORY'])

ValueError:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

最佳答案

您的第二次尝试非常接近,使用 numpy.where 并注意 [its] 条件语句使用 bitwise operators ( & | ^ << >> ~ ).
将所有内容放在一起,我们将得到以下内容;

import pandas as pd
import numpy as np

data = pd.DataFrame({'COL': ['01 thing','02 thing','03 thing']})

print(data)
>>>    COL
>>> 0  01 thing
>>> 1  02 thing
>>> 2  03 thing

data['COL'] = np.where((data['COL'] != '01 thing') | 
                       (data['COL'] != '02 thing'), 'other', data['COL'])

print(data)
>>>    COL
>>> 0  other
>>> 1  other
>>> 2  other

(建议:) 如果你想替换所有不是'01 thing'的记录而不是 '02 thing'你可能想替换 |&反而。另外,我会考虑使用 str.startswith .
将其代入您的 np.where(condition)我们有;

data['COL'] = np.where(~data['COL'].str.startswith('01') &
                       ~data['COL'].str.startswith('02'), 'other', data['COL'])

print(data)
>>>    COL
>>> 0  01 thing
>>> 1  other
>>> 2  02 thing

关于python - 如何在 np.where 中使用两个条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46663638/

相关文章:

python - 从 Celery 中搜索并有选择地删除任务

python - 通过向量的差异对矩阵创建进行向量化(例如,对于 numpy)

python - numpy ndarray 的子类不能按预期工作

Python如何根据文件内容创建UUID

python - Scrapy 飞溅 : screenshot specific element

python - 如何从文件中读取特定行(按行号)?

python - 设置 Gtk.ComboBoxText 默认项?

Python linprog最小化错误——单纯形法

python - 在 numpy/常规 python 中对矩阵求和的更有效方法

numpy - 如何确定一个点是位于 ConvexHull 的内部还是外部?