使用 numpy Python 获取最小索引 [英] Getting the minimum indexes with numpy Python

查看:36
本文介绍了使用 numpy Python 获取最小索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取函数的索引值.但我想获得最小值而不是最大值,就像帖子一样:发布.我试图将下面的函数转换为最小值,而不是最大值以获取索引.

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.

最大值:

a = numpy.array([11, 2, 33, 4, 5, 68, 7])
b = numpy.array([0, 4])
min = numpy.minimum.reduceat(a,b)

索引函数

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

推荐答案

至少,您需要每组中的第一项而不是最后一项.这是通过修改grp_shifted_argmin来实现的:

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]

这篇关于使用 numpy Python 获取最小索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆