Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy compare array to multiple scalars at once

Tags:

python

numpy

Suppose I have an array

a = np.array([1,2,3])

and I want to compare it to some scalar; this works fine like

a == 2 # [False, True, False]

Is there a way I can do such a comparison but with multiple scalars at once? The default behavior when comparing two arrays is to do an elementwise comparison, but instead I want each element of one array to be compared elementwise with the entire other array, like this:

scalars = np.array([1, 2])
some_function(a, scalars)
[[True, False, False],
 [False, True, False]]

Obviously I can do this, e.g., with a for loop and then stacking, but is there any vectorized way to achieve the same result?

like image 581
Nathan Avatar asked Oct 12 '25 17:10

Nathan


1 Answers

Outer product, except it's equality instead of product:

numpy.equal.outer(scalars, a)

or adjust the dimensions and perform a broadcasted comparison:

scalars[:, None] == a