1

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
tony selcuk
  • 709
  • 3
  • 11

1 Answers1

1

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]
jakevdp
  • 77,104
  • 11
  • 125
  • 160
  • Sorry I updated the details what if the list was random,. I want to get the minimum between the 2 indexes. – tony selcuk Jan 30 '21 at 19:32
  • That's exactly what this function does; see the example I added to the answer. – jakevdp Jan 30 '21 at 21:03
  • Hey you have answered my questions a few months ago could you take a look at this post: https://stackoverflow.com/questions/67680199/getting-the-min-and-the-index-of-chunks-numpy-python/67694852#67694852. it is related to this question. – tony selcuk May 25 '21 at 20:22