首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >numpy数组的bisect_right

numpy数组的bisect_right
EN

Stack Overflow用户
提问于 2020-06-13 17:12:25
回答 1查看 174关注 0票数 0

我希望在排序的numpy数组(查询值不在数组中)上找到与查询最接近的较高值的索引。

类似于python标准库中的bisect_right,没有将numpy数组转换为python列表,并利用了数组已排序的事实(即运行时应该是O(log ),就像numpy的searchsorted一样)。

熊猫有这个选项,使用get_loc和'bfill‘选项,但是仅仅为了这个而包含它作为一个依赖项似乎有点过分了……我可能不得不将这个数组同时作为python list和numpy数组保存,但我想知道是否有更合理的解决方案。

编辑:看起来searchsorted做的正是我需要的。

EN

回答 1

Stack Overflow用户

发布于 2020-06-13 17:44:32

我们可以在github上看到bisect_right的代码:

代码语言:javascript
复制
def bisect_right(a, x, lo=0, hi=None):
    """Return the index where to insert item x in list a, assuming a is sorted.
    The return value i is such that all e in a[:i] have e <= x, and all e in
    a[i:] have e > x.  So if x already appears in the list, a.insert(x) will
    insert just after the rightmost x already there.
    Optional args lo (default 0) and hi (default len(a)) bound the
    slice of a to be searched.
    """

    if lo < 0:
        raise ValueError('lo must be non-negative')
    if hi is None:
        hi = len(a)
    while lo < hi:
        mid = (lo+hi)//2
        # Use __lt__ to match the logic in list.sort() and in heapq
        if x < a[mid]: hi = mid
        else: lo = mid+1
    return lo

这是所有numpy兼容的:

代码语言:javascript
复制
import numpy as np

array = np.array([1,2,3,4,5,6])
print(bisect_right(array, 7))
>>> 6
print(bisect_right(array, 0))
>>> 0

要查找与给定数字最接近的较高值的索引,请执行以下操作:

代码语言:javascript
复制
def closest_higher_value(array, value):
    if bisect_right(array, value) < len(array):
        return bisect_right(array, value)
    print("value too large:", value, "is bigger than all elements of:")
    print(array)


print(closest_higher_value(array, 3))
>>> 3
print(closest_higher_value(array, 7))
>>> value too large: 7 is bigger than all elements of:
>>> [1 2 3 4 5 6]
>>> None
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62357673

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档