Reputation: 8477
I would like to pairwise compare (with <=
) all elements of two NumPy ndarray
s 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?
Upvotes: 3
Views: 1036
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
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