Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 418
A. Donda Avatar asked May 05 '26 15:05

A. Donda


1 Answers

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.

like image 190
ranel Avatar answered May 08 '26 04:05

ranel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!