检查两个数组是否具有等效行的最快方法

时间:2013-02-19 19:57:55

标签: python arrays numpy

我试图找出一种更好的方法来检查两个2D数组是否包含相同的行。以下是一个简短的例子:

>>> a
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> b
array([[6, 7, 8],
       [3, 4, 5],
       [0, 1, 2]])

在这种情况下b=a[::-1]。检查两行是否相等:

>>>a=a[np.lexsort((a[:,0],a[:,1],a[:,2]))]
>>>b=b[np.lexsort((b[:,0],b[:,1],b[:,2]))]
>>> np.all(a-b==0)
True

这很棒且相当快。但是当两行“关闭”时会出现问题:

array([[-1.57839867  2.355354   -1.4225235 ],
       [-0.94728367  0.         -1.4225235 ],
       [-1.57839867 -2.355354   -1.4225215 ]]) <---note ends in 215 not 235
array([[-1.57839867 -2.355354   -1.4225225 ],
       [-1.57839867  2.355354   -1.4225225 ],
       [-0.94728367  0.         -1.4225225 ]])

在1E-5的容差范围内,这两个数组按行相等,但是lexsort会告诉你。这可以通过不同的排序顺序来解决,但我想要一个更一般的情况。

我正在想着:

a=a.reshape(-1,1,3)
>>> a-b
array([[[-6, -6, -6],
        [-3, -3, -3],
        [ 0,  0,  0]],

       [[-3, -3, -3],
        [ 0,  0,  0],
        [ 3,  3,  3]],

       [[ 0,  0,  0],
        [ 3,  3,  3],
        [ 6,  6,  6]]])
>>> np.all(np.around(a-b,5)==0,axis=2)
array([[False, False,  True],
       [False,  True, False],
       [ True, False, False]], dtype=bool)
>>>np.all(np.any(np.all(np.around(a-b,5)==0,axis=2),axis=1))
True

如果b中的所有点都接近a中的值,则不会告诉您阵列是否等于行。行数可以是几百,我需要做很多。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您的上一个代码没有按照您的想法执行。它告诉您的是b中的每一行是否都接近a中的一行。如果您将用于外部通话的axis更改为np.anynp.all,则可以检查a中的每一行是否接近b中的某一行}。如果b中的每一行都接近a中的一行,并且a中的每一行都接近b中的一行,则这些集合相等。可能在计算效率上不是很高,但对于中等大小的阵列来说可能非常快:

def same_rows(a, b, tol=5) :
    rows_close = np.all(np.round(a - b[:, None], tol) == 0, axis=-1)
    return (np.all(np.any(rows_close, axis=-1), axis=-1) and
            np.all(np.any(rows_close, axis=0), axis=0))

>>> rows, cols = 5, 3
>>> a = np.arange(rows * cols).reshape(rows, cols)
>>> b = np.arange(rows)
>>> np.random.shuffle(b)
>>> b = a[b]
>>> a
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11],
       [12, 13, 14]])
>>> b
array([[ 9, 10, 11],
       [ 3,  4,  5],
       [ 0,  1,  2],
       [ 6,  7,  8],
       [12, 13, 14]])
>>> same_rows(a, b)
True
>>> b[0] = b[1]
>>> b
array([[ 3,  4,  5],
       [ 3,  4,  5],
       [ 0,  1,  2],
       [ 6,  7,  8],
       [12, 13, 14]])
>>> same_rows(a, b) # not all rows in a are close to a row in b
False

对于不太大的数组,性能是合理的,即使它必须构建(rows, rows, cols)的数组:

In [2]: rows, cols = 1000, 10

In [3]: a = np.arange(rows * cols).reshape(rows, cols)

In [4]: b = np.arange(rows)

In [5]: np.random.shuffle(b)

In [6]: b = a[b]

In [7]: %timeit same_rows(a, b)
10 loops, best of 3: 103 ms per loop