-3

I am wondering if there is a more efficient way to run the comparison (or really many other functions) using numpy.

a = np.array([1,2,5,7])
b = np.array([0,4,6])

np.repeat(a, len(b)).reshape(-1, len(b)) > b

> array([[ True, False, False],
       [ True, False, False],
       [ True,  True, False],
       [ True,  True,  True]])

Basically each output (m, n) is the comparison if A_m > B_n

qwertylpc
  • 2,016
  • 7
  • 24
  • 34

1 Answers1

3

You can use broadcasting to make this operation more efficient. Indeed, repeat creates a new temporary array. Here is the resulting code:

a.reshape(-1, 1) > b
Jérôme Richard
  • 41,678
  • 6
  • 29
  • 59