我将尝试使用numpy数组进行带有掩码索引的向量化求和操作。
例如,不使用掩码:
例如,不使用掩码:
import numpy as np
# data to be used in a vectorized sum operation
data = np.array([[1,0,0,0,0,0],
[0,1,0,0,0,0],
[0,0,1,0,0,0]])
# data indices i wish to sum together
idx = np.array([[0,1,2], # sum data rows 0,1 and 2
[2,1,1]]) # sum data rows 2,1 and 1
# without a mask this is straighforward
print np.sum(data[idx],axis=1)
#[[1 1 1 0 0 0]
# [0 2 1 0 0 0]]
现在有了掩码,我无法找出如何在不循环遍历掩码索引数组的情况下完成它:
# introduce a mask
mask = np.array([[True, True, True], # sum data rows 0,1 and 2
[False, True, True]]) # sum data rows 1 and 1 (masking out idx[1,0])
summed = np.zeros((idx.shape[0],data.shape[1]),dtype='int')
for i in xrange(idx.shape[0]):
summed[i] = np.sum(data[idx[i][mask[i]]],axis=0)
print summed
#[[1 1 1 0 0 0]
#[0 2 0 0 0 0]]
问题
在没有循环的情况下,有没有适当的方法执行这种类型的操作?