【发布时间】:2014-12-22 07:34:44
【问题描述】:
我有一个这样的 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和result[1,1,2:] = True I[1,0] = 0 -> result[1,1,0] = False和result[1,1,1:] = True
这是我当前的实现(正确):
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 循环)?
谢谢!
【问题讨论】:
-
我试图运行你的代码,但它对我不起作用。您能否修改您的问题并使其更清楚?
-
对不起,我的错。 A 是 (2,5,3) 矩阵。我还添加了一个带有布尔转换的打印
标签: python arrays performance python-2.7 numpy