Check if a subarray of the given array

This is a somewhat basic question from a Numpy user newbie: I have a 2D array of 5 rows and 2 columns, you can see it as 10 2d vectors, and I want to check if this vector is inside the table.

For instance:

>>> tableau = array(range(10), dtype = uint8) >>> tableau.shape = (5,2) >>> print tableau [[ 0 1] [ 2 3] [ 4 5] [ 6 7] [ 8 9]] >>> [0, 1] in tableau True 

The last row gives True, but "[0, 2] in the table".

At the moment, I am calculating if the Euclidean distance is 0, but I'm sure there is a simpler answer.

Thanks for any help

+4
source share
3 answers

You can perform a logical reduction in an array of matches:

 ([0, 1] == tableau).all(axis=1).any() 
+6
source

Right ahead, you can use any() to go through the generator by comparing arrays with array_equal .

 from numpy import array_equal in_t = lambda x, t : any((array_equal(a,x) for a in t)) print in_t([0, 2], tableau) print in_t([0, 1], tableau) 
+1
source

I wrote a function to solve this problem, which also handles multidimensional cases. (@ecatmur answer works fine in two dimensions, but doesn't work for 1D or 3D +)

 import numpy as np def haselement(arr,subarr): '''Test if subarr is equal to one of the elements of arr. This is the equivalent of the "in" operator when using lists instead of arrays.''' arr = np.asarray(arr) subarr = np.asarray(subarr) if subarr.shape!=arr.shape[1:]: return False elif arr.ndim<2: return (subarr==arr).any() else: boolArr = (subarr==arr) boolArr.resize([arr.shape[0],np.prod(arr.shape[1:])]) return boolArr.all(axis=1).any() tableau = np.array(range(10), dtype = np.uint8) tableau.shape = (5,2) haselement(tableau,[0,1]) 

1D is handled by the if statement, and ND is handled by resizing the array to 2D for the @ecatmur algorithm to work. Other ways in which I decided to solve this problem include transitions or list loops (which can be actually more efficient, but only if the list is long and the element is close to the beginning); However, it seems more countless.

Here you can also find the function if you want to use it from the library:

https://github.com/davidmashburn/np_utils (obvious disclaimer, I'm the author;))

0
source

All Articles