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!
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().
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“.
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.
__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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With