Home > Software engineering >  How to compare each element of an array with another entire array without loops in numpy
How to compare each element of an array with another entire array without loops in numpy

Time:05-28

Let array A and B be:

import numpy as np

A = np.array([1, 5, 2, 6])
B = np.array([4, 2, 1, 1])

How can I compare each element of array A with array B such that the result would be like shown below

results = np.array([
A[0] > B,
A[1] > B,
A[2] > B,
A[3] > B
])
# resulting in a 2d array like so:
>>> results
[[False False False False] [True True True True] [False False True True] [True True True True]]

CodePudding user response:

The simplest way is to transform A into a column vector and compare it with B, which will trigger the automatic broadcast of both:

>>> A[:, None]
array([[1],
       [5],
       [2],
       [6]])
>>> A[:, None] > B
array([[False, False, False, False],
       [ True,  True,  True,  True],
       [False, False,  True,  True],
       [ True,  True,  True,  True]])
  • Related