A numpy array element that satisfies the condition

You can use the numpy extract function to match an array element. The following code matches the element 'a.' exactly in the array. Suppose I want to match all elements containing '.' how would i do that? Please note that in this case there will be two matches. I would also like to get the row and column numbers of matches. The method should not use extract ; any method will do. Thanks.

 In [110]: x = np.array([['a.','cd'],['ef','g.']]) In [111]: 'a.' == x Out[111]: array([[ True, False], [False, False]], dtype=bool) In [112]: np.extract('a.' == x, x) Out[112]: array(['a.'], dtype='|S2') 
+8
python numpy search
source share
2 answers

You can use string operations :

 >>> import numpy as np >>> x = np.array([['a.','cd'],['ef','g.']]) >>> x[np.char.find(x, '.') > -1] array(['a.', 'g.'], dtype='|S2') 

EDIT: As requested in the comments ... If you want to know indexes where the target condition is true, use numpy.where :

 >>> np.where(np.char.find(x, '.') > -1) (array([0, 1]), array([0, 1])) 

or

 >>> zip(*np.where(np.char.find(x, '.') > -1)) [(0, 0), (1, 1)] 
+9
source share

How about this?

 >>> import numpy as np >>> x = np.array([['a.','cd'],['ef','g.']]) >>> selector = np.array(['.' in s for s in x.flat]).reshape(x.shape) >>> x[selector] array(['a.', 'g.'], dtype='|S2') 
+3
source share

All Articles