[Numpy-discussion] Test if one element of string array is in a defined list

Neil Crighton neilcrighton at gmail.com
Mon Mar 22 08:15:43 EDT 2010


Eric Emsellem <eemselle <at> eso.org> writes:

> Hi
> 
> I would like to test whether strings in a numpy S array are in a given list 
but 
> I don't manage to do so. Any hint is welcome.
> 
> =======================================================
> # So here is an example of what I would like to do
> # I have a String numpy array:
> 
> import numpy as num
> Sarray = num.asarray(["test1","test2","tutu","toto"])
> Farray = num.arange(len(Sarray))
> mylist = ["tutu","hello","why"]
> 

in1d() does what you want.

>>> import numpy as np
>>> Sarray = np.array(["test1","test2","tutu","toto"])
>>> mylist = ["tutu","hello","why"]
>>> np.in1d(Sarray, mylist)
array([False, False,  True, False], dtype=bool)

Be careful of whitespace when doing string comparisons; "tutu " != "tutu" (I've 
been burnt by this in the past).

in1d() is only in more recent versions of numpy (1.4+). If you can't upgrade, 
you can cut and paste the in1d() and unique() routines from here:

http://projects.scipy.org/numpy/browser/branches/datetime/numpy/lib/arraysetops.
py

to use in your own modules.

Cheers, Neil




More information about the NumPy-Discussion mailing list