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:
JavaScript
x
4
1
a = numpy.array([11, 2, 33, 4, 5, 68, 7])
2
b = numpy.array([0, 4])
3
min = numpy.minimum.reduceat(a,b)
4
Index Function
JavaScript
1
9
1
def numpy_argmin_reduceat_v2(a, b):
2
n = a.min()+1 # limit-offset
3
id_arr = np.zeros(a.size,dtype=int)
4
id_arr[b[1:]] = 1
5
shift = n*id_arr.cumsum()
6
sortidx = (a+shift).argsort()
7
grp_shifted_argmin = np.append(b[1:],a.size)-1
8
return sortidx[grp_shifted_argmin] - b
9
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
:
JavaScript
1
9
1
def numpy_argmin_reduceat_v2(a, b):
2
n = a.max() + 1 # limit-offset
3
id_arr = np.zeros(a.size,dtype=int)
4
id_arr[b[1:]] = 1
5
shift = n*id_arr.cumsum()
6
sortidx = (a+shift).argsort()
7
grp_shifted_argmin = b
8
return sortidx[grp_shifted_argmin] - b
9
This correctly returns the index of the minimum value within each sublist:
JavaScript
1
8
1
a = numpy.array([11, 2, 33, 4, 5, 68, 7])
2
b = numpy.array([0, 4])
3
print(numpy_argmin_reduceat_v2(a, b))
4
# [1 0]
5
6
print([np.argmin(a[b[0]:b[1]]), np.argmin(a[b[1]:])])
7
# [1, 0]
8