A. Donda
A. Donda

Reputation: 8477

Add multiple np.newaxis as needed?

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?

Upvotes: 3

Views: 1036

Answers (2)

ranel
ranel

Reputation: 93

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.

Upvotes: 4

Divakar
Divakar

Reputation: 221674

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

Upvotes: 2

Related Questions