Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Less/greater than" comparison of N-dimensional and (N-k)-dimensional numpy arrays

Given two arrays a=np.array([[1, 3], [3, 4]]) and b=np.array([2, 2]).

The goal: get array np.array([False, True]) by operation like a>b. I.e. compare rows (True if each pair of elements satisfy the > operator else False ) instead of elementwise comparison (i.e. I don't want get np.array([[False, True], [True, True]])).

And similar for 3-D and (optional) N-dimensional arrays. E.g.

a1 = np.array([[[1, 2, 1], [2, 3, 2]], [[3, 4, 3], [4, 3, 4]]])
b1 = np.array([1, 1, 1])

Operation like a1 > b1 have to return np.array([[False, True], [True, True]]).

How to do it?

like image 354
kupgov Avatar asked Nov 30 '25 03:11

kupgov


1 Answers

Solution is found: use additionally numpy.all function.

Usage for my examples:

a=np.array([[1, 3], [3, 4]])
b=np.array([2, 2])
numpy.all(a > b, axis=1)

Result:

array([False,  True], dtype=bool)

And

a1 = np.array([[[1, 2, 1], [2, 3, 2]], [[3, 4, 3], [4, 3, 4]]])
b1 = np.array([1, 1, 1])
numpy.all(a1 > b1, axis=2)

Result:

array([[False,  True],
       [ True,  True]], dtype=bool)

numpy.all also allows pass multiple axes (as tuple of ints), so it can be used for any dimensions.

Also numpy allows to use ndarray.all method of numpy arrays. Then examples can be rewritten as (a>b).all(axis=1) and (a1>b1).all(axis=2) respectively.

like image 50
kupgov Avatar answered Dec 01 '25 17:12

kupgov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!