Home > Enterprise >  Python: Numpy / Numba comparing arrays
Python: Numpy / Numba comparing arrays

Time:05-06

I provide a working minimal example without numba decorator. I know that numba gives me an error for a != b with a and b being arrays. Any idea how to make it work with numba?

I have also noted, that numba will work on flatten arrays i.e. a.flatten() != b.flatten(). Unfortunately, I don't want a comparison of last element of column 1 with first element with column 2. I assume, there is a way to compute strides and delete elements from the flat array, but I don't think it is either fast nor readable nor maintainable.

array2d = np.array([[1, 0, 1],
                    [1, 1, 0],
                    [0, 0, 1],
                    [2, 3, 5]])

#@numba.jit(nopython=True)
def TOY_compute_changes(array2d):
    array2d = np.vstack([[False, False, False], array2d[:-1] != array2d[1:]])
    return array2d

TOY_compute_changes(array2d)
array([[False, False, False],
       [False,  True,  True],
       [ True,  True,  True],
       [ True,  True,  True]])

CodePudding user response:

If I am getting you right, this should work:

a = np.array([
    [0, 1, 0],
    [0, 1, 0],
    [0, 1, 0],
])

b = np.array([
    [1, 0, 1],
    [0, 1, 0],
    [0, 1, 0],
])

@numba.jit(nopython=True)
def not_eq(a, b):
    return np.logical_not(a == b)

print(not_eq(a, b))

Output:

[[ True  True  True]
 [False False False]
 [False False False]]

String example:

a = np.array([['a', 'b', 'c'], ['x', 'y', 'z']])
b = np.array([['x', 'y', 'z'], ['x', 'y', 'z']])
print(not_eq(a, b))

Output:

[[ True  True  True]
 [False False False]]
  • Related