numpy.where#
- numpy.where(condition, [x, y, ]/)#
根据 condition 从 x 或 y 中选择元素。
注意
仅提供 condition 时,此函数是
np.asarray(condition).nonzero()的简写。建议直接使用nonzero,因为它对子类也能正确处理。其余的文档仅涵盖提供所有三个参数的情况。- 参数:
- condition类数组,布尔值
为 True 的地方返回 x,否则返回 y。
- x, y类数组
从中选择值的数组。 x、y 和 condition 需要能够广播到某个形状。
- 返回:
- outndarray
当 condition 为 True 时,其中包含 x 的元素,否则包含 y 的元素。
备注
如果所有数组都是一维的,
where等价于[xv if c else yv for c, xv, yv in zip(condition, x, y)]
示例
>>> import numpy as np >>> a = np.arange(10) >>> a array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> np.where(a < 5, a, 10*a) array([ 0, 1, 2, 3, 4, 50, 60, 70, 80, 90])
此函数也可用于多维数组
>>> np.where([[True, False], [True, True]], ... [[1, 2], [3, 4]], ... [[9, 8], [7, 6]]) array([[1, 8], [3, 4]])
x、y 和 condition 的形状会被一起广播
>>> x, y = np.ogrid[:3, :4] >>> np.where(x < y, x, 10 + y) # both x and 10+y are broadcast array([[10, 0, 0, 0], [10, 11, 1, 1], [10, 11, 12, 2]])
>>> a = np.array([[0, 1, 2], ... [0, 2, 4], ... [0, 3, 6]]) >>> np.where(a < 4, a, -1) # -1 is broadcast array([[ 0, 1, 2], [ 0, 2, -1], [ 0, 3, -1]])