Mario
Mario

Reputation: 573

How to compare each element of an array with another entire array without loops in numpy

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

Upvotes: 1

Views: 810

Answers (1)

Mechanic Pig
Mechanic Pig

Reputation: 7751

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

Upvotes: 2

Related Questions