2
我有一個numpy的陣列是這樣的:如何高效地使用索引數組作爲掩碼將numpy數組轉換爲布爾數組?
>>> I
array([[ 1., 0., 2., 1., 0.],
[ 0., 2., 1., 0., 2.]])
和陣列甲這樣的:
>>> 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循環)?
謝謝!
我試圖運行你的代碼,但它不適用於我。你能否修改你的問題並使之更清楚? – mrcl 2014-10-27 07:24:50
對不起,我的錯。 A是(2,5,3)矩陣。我還添加了bool轉換的打印 – Rowandish 2014-10-27 07:29:57