1

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]]
0

1 Answer 1

2

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]])
Sign up to request clarification or add additional context in comments.

Comments

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.