Check if two numpy arrays are identical

前端 未结 7 992
轻奢々
轻奢々 2020-12-10 15:47

Suppose I have a bunch of arrays, including x and y, and I want to check if they\'re equal. Generally, I can just use np.all(x == y) (

7条回答
  •  遥遥无期
    2020-12-10 16:26

    Until this is implemented in numpy natively you can write your own function and jit-compile it with numba:

    import numpy as np
    import numba as nb
    
    
    @nb.jit(nopython=True)
    def arrays_equal(a, b):
        if a.shape != b.shape:
            return False
        for ai, bi in zip(a.flat, b.flat):
            if ai != bi:
                return False
        return True
    
    
    a = np.random.rand(10, 20, 30)
    b = np.random.rand(10, 20, 30)
    
    
    %timeit np.all(a==b)  # 100000 loops, best of 3: 9.82 µs per loop
    %timeit arrays_equal(a, a)  # 100000 loops, best of 3: 9.89 µs per loop
    %timeit arrays_equal(a, b)  # 100000 loops, best of 3: 691 ns per loop
    

    Worst case performance (arrays equal) is equivalent to np.all and in case of early stopping the compiled function has the potential to outperform np.all a lot.

提交回复
热议问题