Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does it mean to be `in` numpy array [duplicate]

Tags:

python

numpy

I have some code, and what I would like it to do is this:

>> x=np.zeros((40,2))
>> x[31]=(12,15)
>> y=x.copy()
>> y[31]=(12,4)

#the following behavior is correct, but the syntax is unwieldy with the
#conversions to float and list, quite annoying

>> e=[12.,15.] 
>> e in x.tolist()
True
>> e in y.tolist()
False

However, in the course of debugging I observed the following odd behavior:

>> e in x
True
>> e in y
True

even though

>> f=(8,93)
>> f in x
False

My question is twofold:

a) What is numpy doing here to produce this result?

b) Is there some way to accomplish this check other than using tolist and float conversion as I have here (without using a python-level for loop)? This design is not obvious and not easily maintainable.

like image 210
aestrivex Avatar asked Dec 02 '25 11:12

aestrivex


1 Answers

I think that in will give you a result equivalent to np.any(y == e) where the dimensions are broadcasted automatically. If you look at y == e (pasted at the bottom of this answer) it has a single True element. Someone more knowledgeable than me will know what's really going on.

There is probably a cleaner way to do it but I would suggest this instead of converting to a list:

>>> np.any(np.all(x == e, axis=-1))
True
>>> np.any(np.all(y == e, axis=-1))
False

Output of y == e looks like

>>> y == e
array([[False, False],
       ...
       [False, False],
       [ True, False],
       [False, False],
       ...
       [False, False]], dtype=bool)
like image 124
YXD Avatar answered Dec 05 '25 02:12

YXD



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!