I am trying to compare all to all elements of two different lenght arrays. Lets say I have an array:
A = np.array([[15,25,22],[200,200,20]])
And second array is an array I want to compare with:
B = np.array([[150., 350.],
[250., 450.],
[150., 350.],
[400., 600.],
[400., 600.],
[650., 850.],
[550., 750.],
[650., 850.]])
What I need is to compare all the elements on index 0 of all arrays in A (A[:, 0]
) with all elements on index 0 in all arrays in array B (B[:, 0]
).
If A is just a simple array such as A=[25,40,25]
, then it is simply done as:
smaller = np.array(A[0] > B[:, 0]).astype('int')
I thought I can transform it to 2d comparison such that
smaller = np.array(A[:, 0] > B[:, 0]).astype('int')
This is not working, error is clear, ValueError: operands could not be broadcast together with shapes (2,) (8,)
. I understand that this way I cannot compare it but I was not able to find the way how to do so.
My desired output would look like this:
[[False, False, False, False, False, False, False, False],
[True, False, True, False, False, False, False, False]]
CodePudding user response:
This is what I can have
np.array([A[i,0] > B[:, 0] for i in range(A.shape[0])])
CodePudding user response:
Thanks to @MichaelSzczesny I got the solution I was looking for. Simply adding [:, None]
to the comparison worked:
smaller = np.array(A[:, 0][:, None] > B[:, 0]).astype('int')
As explained in Use of None in Array indexing in Python, it adds an axis to the array. Thus from
[ 15 200]
We get
[[ 15]
[200]]