【问题标题】:find two closest values in numpy ndarray在 numpy ndarray 中找到两个最接近的值
【发布时间】:2021-08-24 19:44:39
【问题描述】:

我有一个像这样的 numpy ndarray

np.array(
[[40.26164428, 63.50590524, 58.30951895],
 [50.99019514, 69.0651866 , 60.44005295],
 [20.24845673, 14.31782106, 58.52349955],
 [54.58937626, 53.03772242, 21.09502311],
 [56.75385449, 57.5847202 ,  1.41421356]])

(注意:我生成的数组总是不同的形状(这个数组的形状是 (5, 3) 但它可以是 (2, 2) (4, 1)...), 所以这不是一个 3D 坐标数组,它只是这样生成的)

我需要找到生成数组的两个最接近的值并返回它们的索引,在这种情况下,值是58.3095189558.52349955,应该返回坐标[0, 2] and [2, 2]

我尝试使用 cKDtree,但这不是坐标数组,因此在这种情况下不起作用,我该怎么做?

【问题讨论】:

    标签: python numpy numpy-ndarray


    【解决方案1】:

    当有人指出单线时,我会感到尴尬,但这是一种方法。

    我将数组展平,然后对其进行排序,然后找到每个元素之间的增量。找到最小增量。现在,从排序后的数组中,我知道两个最接近的元素的值。 argwhere 然后给我坐标。

    import numpy as np
    
    data = np.array(
    [[40.26164428, 63.50590524, 58.30951895],
     [50.99019514, 69.0651866 , 60.44005295],
     [20.24845673, 14.31782106, 58.52349955],
     [54.58937626, 53.03772242, 21.09502311],
     [56.75385449, 57.5847202 ,  1.41421356]])
    
    
    order = np.sort(data.reshape(-1))
    delta = np.diff(order)
    am = np.argmin(delta)
    print( np.argwhere(data == order[am]))
    print( np.argwhere(data == order[am+1]))
    

    输出:

    C:\tmp>python x.py
    [[0 2]]
    [[2 2]]
    

    【讨论】:

    • 最后你有额外的一对 [] ,这就是为什么你得到 3 个数字而不是 2 个数字,结果证明 numpy 对 delta 部分有功能,所以你也可以改变它: np.diff(order)
    【解决方案2】:

    如果我理解正确,它们在数组中的位置是无关紧要的,所以在这种情况下很简单,将数字放在一个列表中,使其记住它们的原始位置,然后对其进行排序并找到两个连续的最小差异元素

    >>> import itertools
    >>> def pairwise(iterable):
            a,b = itertools.tee(iterable)
            next(b,None)
            return zip(a,b)
    
    >>> data=[[40.26164428, 63.50590524, 58.30951895],
     [50.99019514, 69.0651866,  60.44005295],
     [20.24845673, 14.31782106, 58.52349955],
     [54.58937626, 53.03772242, 21.09502311],
     [56.75385449, 57.5847202,   1.41421356]]
    >>> linear=[ (value,x,y) for x,row in enumerate(data) for y,value in enumerate(row)]
    >>> linear.sort(key=lambda x:x[0])
    >>> min(pairwise(linear),key=lambda pair: abs(pair[0][0]-pair[1][0]))
    ((58.30951895, 0, 2), (58.52349955, 2, 2))
    >>> 
    

    【讨论】:

      猜你喜欢
      • 2012-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-15
      • 1970-01-01
      • 2015-03-01
      • 1970-01-01
      相关资源
      最近更新 更多