检查两个2D numpy数组的公共元素(按行或按列) [英] Check common elements of two 2D numpy arrays, either row or column wise
问题描述
给出两个分别为 nx3
和 mx3
的 numpy
数组,这是一种确定行索引(计数器)的有效方法,其中行是在两个数组中相同.例如,我有以下解决方案,即使没有更大的数组,它的速度也很慢
Given two numpy
arrays of nx3
and mx3
, what is an efficient way to determine the row indices (counter) wherein the rows are common in the two arrays. For instance I have the following solution, which is significantly slow for not even much larger arrays
def arrangment(arr1,arr2):
hits = []
for i in range(arr2.shape[0]):
current_row = np.repeat(arr2[i,:][None,:],arr1.shape[0],axis=0)
x = current_row - arr1
for j in range(arr1.shape[0]):
if np.isclose(x[j,0],0.0) and np.isclose(x[j,1],0.0) and np.isclose(x[j,2],0.0):
hits.append(j)
return hits
它检查 arr1
中是否存在 arr2
的行,并返回与行匹配的 arr1
的行索引.我需要这种安排始终按照 arr2
的行顺序升序.例如给出
It checks if rows of arr2
exist in arr1
and returns the row indices of arr1
where the rows match. I need this arrangement to be always sequentially ascending in terms of rows of arr2
. For instance given
arr1 = np.array([[-1., -1., -1.],
[ 1., -1., -1.],
[ 1., 1., -1.],
[-1., 1., -1.],
[-1., -1., 1.],
[ 1., -1., 1.],
[ 1., 1., 1.],
[-1., 1., 1.]])
arr2 = np.array([[-1., 1., -1.],
[ 1., 1., -1.],
[ 1., 1., 1.],
[-1., 1., 1.]])
该函数应返回:
[3, 2, 6, 7]
推荐答案
快速而肮脏的答案
(arr1[:, None] == arr2).all(-1).argmax(0)
array([3, 2, 6, 7])
更好的答案
照顾机会 arr2
中的行与 arr1
t = (arr1[:, None] == arr2).all(-1)
np.where(t.any(0), t.argmax(0), np.nan)
array([ 3., 2., 6., 7.])
@Divakar指出的 np.isclose
解释了比较浮点数时的舍入误差
As pointed out by @Divakar np.isclose
accounts for rounding error in comparing floats
t = np.isclose(arr1[:, None], arr2).all(-1)
np.where(t.any(0), t.argmax(0), np.nan)
这篇关于检查两个2D numpy数组的公共元素(按行或按列)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!