将条件逻辑表示为数组运算

numpy.where函数是x if condtion else y 的矢量化版本

xarr = np.array([1.1, 1.2, 1.3, 1.4, 1.5])
yarr = np.array([2.1, 2.2, 2.3, 2.4, 2.5])
cond = np.array([True, False, True, True, False])

根据cond中的值选取xarr和yarr。当cond中的值为True时,选取xarr的值,否则是yarr的值。

result = [(x if c else y)
          for x, y, c in zip(xarr, yarr, cond)]
result

上述方式对于大数组的处理速度不是很快,因为完全是由Python完成。

使用np.where的改写

result = np.where(cond, xarr, yarr)
result

np.where的第二个和第三个参数不必是数组,可以是标量值。

假设,有一个随机数据组成的矩阵,希望对正值替换为2,负值替换为-2

arr = randn(4, 4)
arr
np.where(arr > 0, 2, -2)
np.where(arr > 0, 2, arr) # set only positive values to 2

将复杂的条件判断

result = []
for i in range(n):
    if cond1[i] and cond2[i]:
        result.append(0)
    elif cond1[i]:
        result.append(1)
    elif cond2[i]:
        result.append(2)
    else:
        result.append(3)

改写为np.where方式

np.where(cond1 & cond2, 0,
         np.where(cond1, 1,
                  np.where(cond2, 2, 3)))

布尔型数组

布尔值会被强制转换为1和0,因此常使用sum对布尔型数组中的True值计数

arr = randn(100)
(arr > 0).sum() # Number of positive values

any用于测试数组中是否存在一个或多个True;all则检查数组中所有值是否都是True

bools = np.array([False, False, True, False])
bools.any()
bools.all()

results matching ""

    No results matching ""