Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to test if a row is in an array

This seems like a simple question, but I haven't been able to find a good answer.

I'm looking for a pythonic way to test whether a 2d numpy array contains a given row. For example:

myarray = numpy.array([[0,1],
                       [2,3],
                       [4,5]])

myrow1 = numpy.array([2,3])
myrow2 = numpy.array([2,5])
myrow3 = numpy.array([0,3])
myrow4 = numpy.array([6,7])

Given myarray, I want to write a function that returns True if I test myrow1, and False if I test myrow2, myrow3 and myrow4.

I tried the "in" keyword, and it didn't give me the results I expected:

>>> myrow1 in myarray
True
>>> myrow2 in myarray
True
>>> myrow3 in myarray
True
>>> myrow4 in myarray
False

It seems to only check if one or more of the elements are the same, not if all elements are the same. Can someone explain why that's happening?

I can do this test element by element, something like this:

def test_for_row(array,row):
    numpy.any(numpy.logical_and(array[:,0]==row[0],array[:,1]==row[1]))

But that's not very pythonic, and becomes problematic if the rows have many elements. There must be a more elegant solution. Any help is appreciated!

like image 439
Emma Avatar asked Jul 03 '11 05:07

Emma


People also ask

How do you check whether a NumPy array contains a specified row?

This can be done by using simple approach as checking for each row with the given list but this can be easily understood and implemented by using inbuilt library functions numpy. array. tolist().

How do you check if something is in a NumPy array?

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 check if an element is in a array Python?

We can use the in-built python List method, count(), to check if the passed element exists in the List. If the passed element exists in the List, the count() method will show the number of times it occurs in the entire list.

What is __ Array_interface __?

__array_interface__ A dictionary of items (3 required and 5 optional). The optional keys in the dictionary have implied defaults if they are not provided. The keys are: shape (required) Tuple whose elements are the array size in each dimension.


1 Answers

The SO question below should help you out, but basically you can use:

any((myrow1 == x).all() for x in myarray)

Numpy.Array in Python list?

like image 146
rolling stone Avatar answered Sep 28 '22 07:09

rolling stone