有沒有辦法擺脫下面的代碼中的循環,並用矢量化操作代替它?向量化每個矩陣行的變量範圍的numpy.argmin搜索
給定一個數據矩陣,對於每一行,我想找到適合在單獨數組中定義的範圍內(每行)的最小值的索引。
下面是一個例子:
import numpy as np
np.random.seed(10)
# Values of interest, for this example a random 6 x 100 matrix
data = np.random.random((6,100))
# For each row, define an inclusive min/max range
ranges = np.array([[0.3, 0.4],
[0.35, 0.5],
[0.45, 0.6],
[0.52, 0.65],
[0.6, 0.8],
[0.75, 0.92]])
# For each row, find the index of the minimum value that fits inside the given range
result = np.zeros(6).astype(np.int)
for i in xrange(6):
ind = np.where((ranges[i][0] <= data[i]) & (data[i] <= ranges[i][1]))[0]
result[i] = ind[np.argmin(data[i,ind])]
print result
# Result: [35 8 22 8 34 78]
print data[np.arange(6),result]
# Result: [ 0.30070006 0.35065639 0.45784951 0.52885388 0.61393513 0.75449247]
做什麼,如果所有的'data'超出'range'對於一個給定的行? –