【问题标题】:Filtering close values within multidimensional arrays Python过滤多维数组Python中的关闭值
【发布时间】:2021-11-02 02:45:37
【问题描述】:

下面的代码将数组a 与其他数组b,c,d 进行比较。 comparison 函数应该显示other 数组在a 内的索引。第一列和第二列必须相等才能返回True 输出。例如,如果a[0,123.5] 并且b[1,123] 那么它将返回False 因为第一列值不等于0,1 但如果c 也是0 那么应该是True。如果值在两个比较数组中,例如 [1,123]ab 内,它是 5th 在 a 内的索引和 4th 在 b 内的索引,但由于为a 记录索引,输出将为5。我正在尝试将math.isclose(a, other, rel_tol= 0.5) 函数放置给它们,因此如果第二列的值最多相差0.5,它们仍将返回True,因此即使[0,123.5][0,123] 之间存在差异, math.isclose(123.5, 123, rel_tol= 0.5)0.5 的差异,它仍然返回 True。我怎样才能得到预期的输出?

import numpy as np 
import math

a = np.array([[0,12],[1,40],[0,55],[1,23],[0,123.5],[1,4]])
b = np.array([[0,3],[1,10],[0,55],[1,34],[1,122],[0,123]])
c = np.array([[0,3],[1,10],[0,55],[1,34],[1,122],[0,121]])
d = np.array([[0,40],[1,55],[0,24],[0,123],[0,4]])
e = np.array([[1,40.2],[1,55]])

def comp(a, other):
    
    try: 
        nrows, ncols = a.shape
        dtype={'names':['f{}'.format(i) for i in range(ncols)],
               'formats':ncols * [a.dtype]}

        C = np.intersect1d(a.view(dtype), other.view(dtype))

        # This last bit is optional if you're okay with "C" being a structured array...
        C = C.view(a.dtype).reshape(-1, ncols)
        print("\n",C)
    except:
        print("No difference")

comp(a, b)
comp(a, c)
comp(a, d)
comp(a, e)

预期输出:

[[  0  55]
 [  0 123]]

[[0,55]]

[[  0 123]]

[[ 1 40]]

【问题讨论】:

    标签: python arrays numpy multidimensional-array indexing


    【解决方案1】:

    您可以为此使用np.allclose

    >>> import numpy as np
    >>>
    >>>
    >>>
    >>> a = np.array([[0,12],[1,40],[0,55],[1,23],[0,123.5],[1,4]])
    >>> b = np.array([[0,3],[1,10],[0,55],[1,34],[1,122],[0,123]])
    >>>
    >>>
    >>>
    >>> for i in a:
    ...     for j in b:
    ...         if np.allclose(i, j, atol=0.5):
    ...             print(i, j)
    ... 
    [ 0. 55.] [ 0 55]
    [  0.  123.5] [  0 123]
    

    您需要适当地设置atol 参数,以便满足您对“关闭”的定义。

    【讨论】:

      猜你喜欢
      • 2018-11-15
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      • 2016-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多