在Python中求两个矩阵在公差内的交集?

2024-04-24 03:20:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我在寻找两个不同大小矩阵的交集的最有效的方法。每个矩阵有三个变量(列)和不同数量的观察值(行)。例如,矩阵A:

a = np.matrix('1 5 1003; 2 4 1002; 4 3 1008; 8 1 2005')
b = np.matrix('7 9 1006; 4 4 1007; 7 7 1050; 8 2 2003'; 9 9 3000; 7 7 1000')

如果我将每个列的容差设置为col1 = 1col2 = 2、和{},那么我需要一个函数,它可以输出a和{}中在各自公差范围内的索引,例如:

^{pr2}$

从索引可以看出,a的元素2在b的元素1的公差范围内。在

我想我可以循环遍历矩阵a的每个元素,检查它是否在b中每个元素的公差范围内,然后这样做。但对于非常大的数据集,它似乎效率低下。在

有什么建议可以替代循环方法来实现这一点?在


Tags: 数据方法函数元素数量np矩阵matrix
1条回答
网友
1楼 · 发布于 2024-04-24 03:20:25

如果您不介意使用NumPy数组,那么可以利用^{}来实现矢量化解决方案。这是实现-

# Set tolerance values for each column
tol = [1, 2, 10]

# Get absolute differences between a and b keeping their columns aligned
diffs = np.abs(np.asarray(a[:,None]) - np.asarray(b))

# Compare each row with the triplet from `tol`.
# Get mask of all matching rows and finally get the matching indices
x1,x2 = np.nonzero((diffs < tol).all(2))

样本运行-

^{pr2}$

Large datasize case:如果您使用的是导致内存问题的大型数据集,并且您已经知道列的数量是一个很小的3,那么您可能希望有一个最小的3迭代循环,并节省大量的内存占用,如下-

na = a.shape[0]
nb = b.shape[0]
accum = np.ones((na,nb),dtype=bool)
for i in range(a.shape[1]):
    accum &=  np.abs((a[:,i] - b[:,i].ravel())) < tol[i]
x1,x2 = np.nonzero(accum)

相关问题 更多 >