I'm getting different behavior from in1d
depending on which machine I run my script on.
On my desktop (numpy version 1.6.2) I try
x = np.array('a b c d e f g h i j'.split())
np.in1d(x, set(['f', 'e', 'r']))
array([False, False, False, False, True, True, False, False, False, False], dtype=bool)
which is what I expected. On my laptop (version 1.8.1) The result is all False
, which is not what I want.
Playing around a little, I discovered that
np.in1d(x, ['f', 'e', 'r'])
works in both versions, but I don't understand why the function doesn't behave as expected when passed a set.
I do not know when/if a change was made, but this is because the second argument of np.in1d
has to be an array-like. Sets are not array-likes because they are not ordered.
You can (kind of) see this issue if you try to convert a set to an array. Instead of a 1-d array like you might expect, you get a strange 0-d object.
a = np.array(set([1, 3, 5, 6]))
print(repr(a))
# array({1, 3, 5, 6}, dtype=object)
print(a.shape)
# ()
You could argue that it should raise an exception or something instead of simply going through with the operation, but that's how the code currently works. It doesn't seem like np.in1d
(or any similar functions) will be modified, so it's best to get into the habit of converting sets to lists before passing them to numpy functions.
There is an existing issue regarding this on github.
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