python - 如何在 python (numpy) 中找到两个 x,y 坐标数组之间的可容忍重叠

标签 python performance numpy

我有两个不同长度的二维数组。如何在一定的公差范围内找到这些数组沿零轴的重叠?例如如果

a1 = [1,1.2]
a2 = [1,2.1]
a3 = [1,1.1]
a4 = [.89, 2.21]
a5 = [0,0] 
coors1 = np.array( [ a1, a2 ])
coors2 = np.array( [ a3, a4, a5 ])

然后我想要一个函数overlap来给出

overlap( coors1,coors2, tolerance=0.1)
#[ [1,1.2] ]
overlap( coors1, coors2, tolerance=0.12)
#[ [ 1,1.2], [1, 2.1] ]

我想出了类似的东西

def overlap(coor1, coors2, tolerance ) :
    return [ c1 for c1 in coors1 for c2 in coors2 if np.all( np.isclose( c1, c2, atol=tolerance))   ]

但看起来可能会很慢......

对于那些感兴趣并愿意插话的人

我的问题源于我正在做的一些数据库工作。我有几个数据库,每个数据库都有 x,y 坐标作为列。还有代表在这些坐标处执行的各种测量的列。我需要根据坐标比较数据库,考虑到某些坐标会出现浮点舍入误差。

最佳答案

如果我的问题正确,你可以使用broadcasting以矢量化方式解决它 -

def overlap(coors1, coors2, tolerance ):

    # Perform elementwise absolute subtractions between input arrays 
    sub_abs_vals = np.abs(coors1[None,:,:] - coors2[:,None,:])

    # Check for ANY equality along 0-th axis & ALL equality along 2-nd axis.
    # Return the corresponding row from first input array.
    return coors1[np.all(np.any(sub_abs_vals<=tolerance,axis=0),axis=1)]

验证结果 -

In [124]: coors1
Out[124]: 
array([[ 1. ,  1.2],
       [ 1. ,  2.1]])

In [125]: coors2
Out[125]: 
array([[ 1.  ,  1.1 ],
       [ 0.89,  2.21],
       [ 0.  ,  0.  ],
       [ 1.  ,  1.06]])

In [126]: def overlap1(coors1, coors2, tolerance ) :
     ...:     return [ c1 for c1 in coors1 for c2 in coors2 if np.all( np.isclose( c1, c2, atol=tolerance))   ]
     ...: 
     ...: 
     ...: def overlap2(coors1, coors2, tolerance ):
     ...:     sub_abs_vals = np.abs(coors1[None,:,:] - coors2[:,None,:])
     ...:     return coors1[np.all(np.any(sub_abs_vals<=tolerance,axis=0),axis=1)]
     ...: 

In [127]: overlap1(coors1, coors2, 0.1 )
Out[127]: [array([ 1. ,  1.2])]

In [128]: overlap2(coors1, coors2, 0.1 )
Out[128]: array([[ 1. ,  1.2]])

In [129]: overlap1(coors1, coors2, 0.12 )
Out[129]: [array([ 1. ,  1.2]), array([ 1. ,  2.1])]

In [130]: overlap2(coors1, coors2, 0.12 )
Out[130]: 
array([[ 1. ,  1.2],
       [ 1. ,  2.1]])

关于python - 如何在 python (numpy) 中找到两个 x,y 坐标数组之间的可容忍重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31332347/

相关文章:

sql - 在 pl/sql 中使用 Bulk Collect/FORALL 转换 Merge 子句

PHP : What is the benefit of spl_autoload_register? 包含的性能

arrays - 从 numpy 数组计算峰度?

Python程序第一次执行时间太长?

python - 您最初选择机器学习算法/进行初始设置的经验法则是什么?

python - 检测 Pandas 数据框中特定列的行中的异常值

python - Pyautogui 无法在 Mac 上运行? (卡特琳娜)

python - 替换字典中所有字典中的冗余键名称

python - 列重命名为 : switching between numbers and letters

python - 创建对象时 Class() vs self.__class__()?