3

I would like to pairwise compare (with <=) all elements of two NumPy ndarrays A and B, where both arrays can have arbitrary dimensions m and n, such that the result is an array of dimension m + n.

I know how to do it for given dimension of B.

  1. scalar: A <= B

  2. one-dimensional: A[..., np.newaxis] <= B

  3. two-dimensional: A[..., np.newaxis, np.newaxis] <= B

Basically, I'm looking for a way to insert as many np.newaxis as there are dimensions in the second array.

Is there a syntax like np.newaxis * B.ndim, or another way?

A. Donda
  • 8,381
  • 2
  • 20
  • 49

2 Answers2

3

The accepted answer solves OP's problem, but does not address the question in the title in the optimal way. To add multiple np.newaxis, you can do

A[(...,) + (np.newaxis,) * B.ndim]

which is maybe more readable than the reshape solution.

ranel
  • 71
  • 2
2

There's builtin for that -

np.less_equal.outer(A,B)

Another way would be with reshaping to accomodate new axes -

A.reshape(list(A.shape)+[1]*B.ndim) <= B
Divakar
  • 218,885
  • 19
  • 262
  • 358
  • Yes, `.outer` seems to be exactly what I'm looking for, thanks! The "another way" probably works, too, but it's much more cumbersome and hard to understand. – A. Donda Oct 17 '20 at 21:52
  • Is there a binary operator that creates a 2-tuple? If so, `.outer` would make a much nicer answer to https://stackoverflow.com/questions/11144513/cartesian-product-of-x-and-y-array-points-into-single-array-of-2d-points – A. Donda Oct 17 '20 at 21:54
  • 1
    @A.Donda Good idea, but there's none (None/np.newaxis pun not intended). – Divakar Oct 17 '20 at 21:57