[Numpy-discussion] array membership test?

josef.pktd@gmai... josef.pktd@gmai...
Tue May 5 22:42:26 CDT 2009

On Tue, May 5, 2009 at 10:37 PM, Mark Wendell <mark.wendell@gmail.com> wrote:
> Is there a numpy equivalent of python's membership test (eg,  "5 in
> [1,3,4,5]" returns True)? I'd like a quick way to test if a given
> number is in an array, without stepping through the elements
> individually. I realize this can be tricky with floats, but if there
> is such a thing for ints, that would be great.

>>> import numpy as np
>>> (5==np.array([1,3,4,5])).any()

>>> np.setmember1d([5],[1,3,4,5])
array([ True], dtype=bool)
>>> np.setmember1d([3,5,6],[1,3,4,5])
array([ True,  True, False], dtype=bool)
>>> np.setmember1d([3.1,5.3,6.],[1.,3.1,4.,5.3])
array([ True,  True, False], dtype=bool)

setmember1d requires unique elements in both arrays, but there is a
version for non-unique arrays in a trac ticket


More information about the Numpy-discussion mailing list