I am trying to get the index values of the function. But I want to get the minimum instead of the maximum values of just like the post: post. I have tried to convert the function below to work for the minimum values unlike the maximum values to getting the indexes.
Max Values:
a = numpy.array([11, 2, 33, 4, 5, 68, 7]) b = numpy.array([0, 4]) min = numpy.minimum.reduceat(a,b)
Index Function
def numpy_argmin_reduceat_v2(a, b): n = a.min()+1 # limit-offset id_arr = np.zeros(a.size,dtype=int) id_arr[b[1:]] = 1 shift = n*id_arr.cumsum() sortidx = (a+shift).argsort() grp_shifted_argmin = np.append(b[1:],a.size)-1 return sortidx[grp_shifted_argmin] - b
Advertisement
Answer
For the minimum, you need the first item in each group rather than the last. This is accomplished by modifying grp_shifted_argmin
:
def numpy_argmin_reduceat_v2(a, b): n = a.max() + 1 # limit-offset id_arr = np.zeros(a.size,dtype=int) id_arr[b[1:]] = 1 shift = n*id_arr.cumsum() sortidx = (a+shift).argsort() grp_shifted_argmin = b return sortidx[grp_shifted_argmin] - b
This correctly returns the index of the minimum value within each sublist:
a = numpy.array([11, 2, 33, 4, 5, 68, 7]) b = numpy.array([0, 4]) print(numpy_argmin_reduceat_v2(a, b)) # [1 0] print([np.argmin(a[b[0]:b[1]]), np.argmin(a[b[1]:])]) # [1, 0]