使用Numpy以向量化方式检索多个值的索引 [英] Retrieve indexes of multiple values with Numpy in a vectorization way

查看:148
本文介绍了使用Numpy以向量化方式检索多个值的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了在numpy数组中获取与"99"值相对应的索引,我们要做:

In order to get the index corresponding to the "99" value in a numpy array, we do :

mynumpy=([5,6,9,2,99,3,88,4,7))
np.where(my_numpy==99)

如果我想获得与以下值99,55,6,3,7对应的索引怎么办?显然,可以通过一个简单的循环来完成此操作,但是我正在寻找更多的矢量化解决方案.我知道Numpy非常强大,所以我认为它可能存在类似的东西.

What if, I want to get the index corresponding to the following values 99,55,6,3,7? Obviously, it's possible to do it with a simple loop but I'm looking for a more vectorization solution. I know Numpy is very powerful so I think it might exist something like that.

所需的输出:

searched_values=np.array([99,55,6,3,7])
np.where(searched_values in mynumpy)
[(4),(),(1),(5),(8)]

推荐答案

这是使用np.searchsorted-

def find_indexes(ar, searched_values, invalid_val=-1):
    sidx = ar.argsort()
    pidx = np.searchsorted(ar, searched_values, sorter=sidx)
    pidx[pidx==len(ar)] = 0
    idx = sidx[pidx]
    idx[ar[idx] != searched_values] = invalid_val
    return idx

样品运行-

In [29]: find_indexes(mynumpy, searched_values, invalid_val=-1)
Out[29]: array([ 4, -1,  1,  5,  8])

对于通用无效值说明符,我们可以使用np.where-

For a generic invalid value specifier, we could use np.where -

def find_indexes_v2(ar, searched_values, invalid_val=-1):
    sidx = ar.argsort()
    pidx = np.searchsorted(ar, searched_values, sorter=sidx)
    pidx[pidx==len(ar)] = 0
    idx = sidx[pidx]
    return np.where(ar[idx] == searched_values, idx, invalid_val)

样品运行-

In [35]: find_indexes_v2(mynumpy, searched_values, invalid_val=None)
Out[35]: array([4, None, 1, 5, 8], dtype=object)

# For list output
In [36]: find_indexes_v2(mynumpy, searched_values, invalid_val=None).tolist()
Out[36]: [4, None, 1, 5, 8]

这篇关于使用Numpy以向量化方式检索多个值的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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