3

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.

aestrivex
  • 5,170
  • 2
  • 27
  • 44
  • This is hard to google for, but it helps to know that `in` calls the `__contains__` method. See here for more info: http://stackoverflow.com/q/18320624/1730674 and https://github.com/numpy/numpy/issues/3016 and http://www.mail-archive.com/numpy-discussion@scipy.org/msg31578.html – askewchan Oct 30 '13 at 18:43

1 Answers1

2

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)
YXD
  • 31,741
  • 15
  • 75
  • 115