【问题标题】:find the array index which its element is most near greater than a value找到其元素最接近大于某个值的数组索引
【发布时间】:2020-04-20 23:07:17
【问题描述】:

我有一个排序数组。

x = [1, 10, 12, 16, 19, 20, 21, ....]

对于介于[x[0], x[-1]] 之间的任何给定数字y,我想找到最接近大于y 的元素的索引,例如,如果y = 0,则返回0 ,如果y = 18,则返回4

有没有可用的功能?

【问题讨论】:

    标签: pandas numpy


    【解决方案1】:

    无需任何外部库,即可使用bisect

    i = bisect.bisect_right(x, y)
    

    i 将是您想要的元素的索引。

    【讨论】:

    • 谢谢,太棒了!
    【解决方案2】:

    鉴于排序的性质,我们可以使用np.searchsorted -

    idx = np.searchsorted(x,y,'right')
    

    【讨论】:

      【解决方案3】:

      你可以在差的绝对值上使用numpy.argmin

      import numpy as np
      x = np.array([1, 10, 12, 16, 19, 20, 21])
      
      def find_closest(x,y):
          return (np.abs(x-y)).argmin()
      
      for y in [0,18]:
          print(find_closest(x,y))
      
      0
      4
      

      【讨论】:

      • 效率不够,因为我们处理的是排序数组
      猜你喜欢
      • 2011-08-29
      • 2021-02-11
      • 2018-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多