Add multiple np.newaxis as needed?

Question:

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?

Asked By: A. Donda

||

Answers:

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
Answered By: Divakar

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.

Answered By: ranel
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.