【发布时间】:2016-03-17 16:38:05
【问题描述】:
numpy.where()有些东西我不明白:
假设我有一个 2D numpy ndarray:
import numpy as np
twodim = np.array([[1, 2, 3, 4], [1, 6, 7, 8], [1, 1, 1, 12], [17, 3, 15, 16], [17, 3, 18, 18]])
现在,想创建一个函数来“检查”这个 numpy 数组的各种条件。
array([[ 1, 2, 3, 4],
[ 1, 6, 7, 8],
[ 1, 1, 1, 12],
[17, 3, 15, 16],
[17, 3, 18, 18]])
例如,该数组中的哪些条目 (A) 偶数 (B) 大于 7 (C) 可被 3 整除?
我想为此使用numpy.where(),并遍历该数组的每个条目,最终找到符合所有条件的元素(如果存在这样的条目):
even_entries = np.where(twodim % 2 == 0)
greater_seven = np.where(twodim > 7 )
divisible_three = np.where(twodim % 3 == 0)
如何做到这一点?我不确定如何遍历布尔值...
我可以通过
访问矩阵 (i,j) 的索引np.argwhere(even_entries)
我们可以做类似的事情
import numpy as np
twodim = np.array([[1, 2, 3, 4], [1, 6, 7, 8], [1, 1, 1, 12], [17, 3, 15, 16], [17, 3, 18, 18]])
even_entries = np.where(twodim % 2 == 0)
greater_seven = np.where(twodim > 7 )
divisible_three = np.where(twodim % 3 == 0)
for row in even_entries:
for item in row:
if item: #equivalent to `if item == True`
for row in greater_seven:
for item in row:
if item: #equivalent to `if item == True`
for row in divisible_three:
for item in row:
if item: #equivalent to `if item == True`
# something like print(np.argwhere())
有什么建议吗?
EDIT1:下面的好主意。正如@hpaulj 提到的“您的测试会产生一个与 twodim 形状相同的布尔矩阵” 这是我在玩弄时遇到的一个问题——并非所有条件都会产生与我的起始矩阵相同形状的矩阵。例如,假设我正在比较数组元素的左侧或右侧(即水平方向)是否有匹配的数组
twodim[:, :-1] == twodim[:, 1:]
这导致一个 (5,3) 布尔数组,而我们的原始矩阵是一个 (5,4) 数组
array([[False, False, False],
[False, False, False],
[ True, True, False],
[False, False, False],
[False, False, True]], dtype=bool)
如果我们在垂直方向上做同样的事情,结果是一个 (4,4) 布尔数组,而原始矩阵是 (5,4)
twodim[:-1] == twodim[1:]
array([[ True, False, False, False],
[ True, False, False, False],
[False, False, False, False],
[ True, True, False, False]], dtype=bool)
如果我们想知道哪些条目有个垂直和水平对,那么弄清楚我们所处的维度并非易事。
【问题讨论】:
-
不要使用
where。我不知道为什么新的 NumPy 用户会继续使用它,但这并不是一个好主意。通过直接使用布尔掩码,您可以更轻松地完成这项工作。
标签: python numpy iteration where