Test if one element of string array is in a defined list
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"] # and I would like to do: result = num.where(Sarray in mylist, Farray, 0) ======================================================= ===> but of course I get a ValueError since the first test syntax is wrong. I would like to be able to do: Sarray in mylist and get the output: array([False, False, True, False],dtype=bool) since only the 3rd string "tutu" of Sarray is in mylist. Any input is welcome. cheers Eric
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/arrayset.... py to use in your own modules. Cheers, Neil
participants (2)
-
Eric Emsellem
-
Neil Crighton