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.
scalar: A <= B
one-dimensional: A[..., np.newaxis] <= B
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With