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

I want to compare the A array to each element of B. In other words I'm lookin for a function which do the following computations :

A>2
A>5
(array([ True, False,  True,  True]), array([False, False, False,  True]))
6
  • [A > b for b in B]? Commented Aug 13, 2018 at 12:41
  • Yes lol. I was looking for something more numpyic but that's fine also. Commented Aug 13, 2018 at 12:41
  • 8
    You can use broadcasting A>B[:,None] Commented Aug 13, 2018 at 12:42
  • Wonderful@Brenlla, thks. Could you esplain why does it work? Commented Aug 13, 2018 at 12:44
  • By adding a an extra dimension to B, it sort off "expands" the last dimension of B to match the dimension of A. I know it doesn't make a lot of sense, but it is posibly the most important feature of numpy. For more details see here Commented Aug 13, 2018 at 12:52

1 Answer 1

7

Not particularly fancy but a list comprehension will work:

[A > b for b in B]

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

You can also use np.greater(), which requires the dimension-adding trick that Brenlla uses in the comments:

np.greater(A, B[:,np.newaxis])

array([[ True, False,  True,  True],
       [False, False, False,  True]], dtype=bool)
Sign up to request clarification or add additional context in comments.

4 Comments

Yeah, right but I prefer the Brenlla version ... A>B[:,None] as it give me a numpy array
Sure, I like that one too! (But you can always just wrap this answer in np.array().)
@hans glick there is an explicit Numpy function for pairwise comparison of two vectors, see updated answer.
I'm confused, is the greater function what you are referring to with your last comment, because that still uses explicit broadcasting. Is there any built in numpy function which produces an n*m output of comparisons without explicit broadcasting (even if such a function just performs broadcasting behind the scenes). I'm fine with doing the broadcasting myself, but if a method exists that wraps it, I'd rather use that for readability

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.