背景
我有两个numpy数组,想以最高效/最快的方式进行一些比较操作。两个数组中都只包含无符号整数。
pairs
是一个n x 2 x 3
数组,其中包含一长串成对的三维坐标(为了方便命名,pairs
数组包含一组配对...)-即
# full pairs array
In [145]: pairs
Out[145]:
array([[[1, 2, 4],
[3, 4, 4]],
.....
[[1, 2, 5],
[5, 6, 5]]])
# each entry contains a pair of 3D coordinates
In [149]: pairs[0]
Out[149]:
array([[1, 2, 4],
[3, 4, 4]])
positions
是一个n x 3
的数组,其中存储了一组三维坐标。
In [162]: positions
Out[162]:
array([[ 1, 2, 4],
[ 3, 4, 5],
[ 5, 6, 3],
[ 3, 5, 6],
[ 6, 7, 5],
[12, 2, 5]])
目标
我想创建一个数组,它是pairs
数组的子集,但只包含最多有一个对在positions数组中的条目 - 即不应该有两个对都在positions数组中。对于一些域信息,每个对将至少有一对位置在positions列表内。
已尝试的方法
我的最初的天真方法是循环遍历pairs
数组中的每个对,并从positions
向量中减去每个对的两个位置,确定在两种情况下是否找到了匹配,这由来自减法操作的两个向量中都存在0来表示:
if (~(positions-pair[0]).any(axis=1)).any() and
(~(positions-pair[1]).any(axis=1)).any():
# both members of the pair were in the positions array -
# these weren't the droids we were looking for
pass
else:
# append this set of pairs to a new matrix
这样做还不错,并利用了一些向量化技术,但可能有更好的方法吗?
对于程序中其他性能敏感的部分,我已经使用Cython重写了一些内容,这带来了巨大的加速,尽管在这种情况下(至少基于一个天真的嵌套for循环实现),这种方法略慢于上面概述的方法。
如果有人有建议,我很乐意进行分析并报告结果(我已经设置好了所有的分析基础设施)。