Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding element of numpy array that satisfies condition

One can use numpy's extract function to match an element in an array. The following code matches an element 'a.' exactly in an array. Suppose I want to match all elements containing '.', how would I do that? Note that in this case, there would be two matches. I'd also like to get the row and column number of the matches. The method doesn't have to 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')
like image 422
Faheem Mitha Avatar asked Dec 06 '11 21:12

Faheem Mitha


People also ask

How do you extract items that satisfy a given condition from 1d array?

If you want to extract elements that meet the condition, you can use ndarray[conditional expression] . Even if the original ndarray is a multidimensional array, a flattened one-dimensional array is returned. A new ndarray is returned, and the original ndarray is unchanged.

How do I check if a NumPy array contains a value?

Using Numpy array, we can easily find whether specific values are present or not. For this purpose, we use the “in” operator. “in” operator is used to check whether certain element and values are present in a given sequence and hence return Boolean values 'True” and “False“.

How do you find the specific element of an array in Python?

An array in Python is used to store multiple values or items or elements of the same type in a single variable. We can access elements of an array using the index operator [] . All you need do in order to access a particular element is to call the array you created.


1 Answers

You can use the 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 per request in the comments... If you want to find out the indexes of 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)]
like image 172
mac Avatar answered Nov 15 '22 15:11

mac