我有一个像这样的 numpy 数组:
>>> I
array([[ 1., 0., 2., 1., 0.],
[ 0., 2., 1., 0., 2.]])
像这样的数组 A:
>>> A = np.ones((2,5,3))
我想获得以下矩阵:
>>> result
array([[[ False, False, True],
[ False, True, True],
[ False, False, False],
[ False, False, True],
[ False, True, True]],
[[ False, True, True],
[ False, False, False],
[ False, False, True],
[ False, True, True],
[ False, False, False]]], dtype=bool)
最好举例说明:
I[0,0] = 1 -> result[0,0,:2] = False
and result[ 1,1,2:] = True
I[1,0] = 0 -> result[1,1,0] = False
和 result[ 1,1,1:] = 真
这是我当前的实现(正确):
result = np.empty((A.shape[0], A.shape[1], A.shape[2]))
r = np.arange(A.shape[2])
for i in xrange(A.shape[0]):
result[i] = r > np.vstack(I[i])
print result.astype(np.bool)
有没有更快的实现方式(避免 for 循环)?
谢谢!
最佳答案
你只需要在I
上添加另一个维度,这样你就可以正确地广播r
:
result = r > I.reshape(I.shape[0],I.shape[1],1)
例如
In [41]: r>I.reshape(2,5,1)
Out[41]:
array([[[False, False, True],
[False, True, True],
[False, False, False],
[False, False, True],
[False, True, True]],
[[False, True, True],
[False, False, False],
[False, False, True],
[False, True, True],
[False, False, False]]], dtype=bool)
关于python - 如何有效地使用索引数组作为掩码将 numpy 数组转换为 bool 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26582211/