如何找到numpy数组中更大的最近值? [英] How to find nearest value that is greater in numpy array?

查看:146
本文介绍了如何找到numpy数组中更大的最近值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取numpy数组中最接近的值的索引,该索引大于我的搜索值。示例: findNearestAbove(np.array([0.,1.,1.4,2。]),1.5)应返回3(索引为2。)。

I would like to obtain the index of the nearest value in a numpy array which is greater than my search value. Example: findNearestAbove(np.array([0.,1.,1.4,2.]), 1.5) should return 3 (the index of 2.).

我知道我可以用 np.abs(a-value).argmin()获取最近的索引,并且我发现 min(a [np.where(a-value> = 0。)[0]])返回所需的数组值。因此, np.where(a == min(a [np.where(a-value> = 0。)[0]]))[0] 可能给我所需的指数。然而,这看起来相当复杂,我担心在多维数组的情况下它可能会破坏。任何建议如何改善这个?

I know that I can get the nearest index with np.abs(a-value).argmin(), and I found out that min(a[np.where(a-value >= 0.)[0]]) returns the desired array value. Hence, np.where(a == min(a[np.where(a-value >= 0.)[0]]))[0] would probably give me the desired index. However, this looks rather convoluted, and I fear that it might break in the case of multi-dimensional arrays. Any suggestions how to improve this?

推荐答案

这是一种方式(我假设你的意思是最接近你的意思是价值而不是位置)

Here is one way (I am assuming that by nearest you mean in terms of value not location)

import numpy as np

def find_nearest_above(my_array, target):
    diff = my_array - target
    mask = np.ma.less_equal(diff, 0)
    # We need to mask the negative differences and zero
    # since we are looking for values above
    if np.all(mask):
        return None # returns None if target is greater than any value
    masked_diff = np.ma.masked_array(diff, mask)
    return masked_diff.argmin()

结果:

>>> find_nearest_above(np.array([0.,1.,1.4,2.]), 1.5)
3
>>> find_nearest_above(np.array([0.,1.,1.4,-2.]), -1.5)
0
>>> find_nearest_above(np.array([0., 1, 1.4, 2]), 3)
>>> 

这篇关于如何找到numpy数组中更大的最近值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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