testing - Pythonic way to test if a row is in an array -


this seems simple question, haven't been able find answer.

i'm looking pythonic way test whether 2d numpy array contains given row. 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, want write function returns true if test myrow1, , false if test myrow2, myrow3 , myrow4.

i tried "in" keyword, , didn't give me results expected:

>>> myrow1 in myarray true >>> myrow2 in myarray true >>> myrow3 in myarray true >>> myrow4 in myarray false 

it seems check if 1 or more of elements same, not if elements same. can explain why that's happening?

i can test element element, this:

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

but that's not pythonic, , becomes problematic if rows have many elements. there must more elegant solution. appreciated!

you can subtract test row array. find out 0 elements, , sum on column wise. matches sum equals number of columns.

for example:

in []: a= arange(12).reshape(4, 3) in []: out[]:  array([[ 0,  1,  2],        [ 3,  4,  5],        [ 6,  7,  8],        [ 9, 10, 11]]) in []: 3== (0== (a- [3, 4, 5])).sum(1) out[]: array([false,  true, false, false], dtype=bool) 

update: based on comments , other answers:
paul's suggestion seems indeed able streamline code:

in []: ~np.all(a- [3, 4, 5], 1) out[]: array([false,  true, false, false], dtype=bool) 

joshadel's answer emphasis more problem related determine 100% reliable manner equality. so, answer valid in situations equality can determined unambiguous manner.

update 2: emma figured out, there exists corner cases paul's solution not produce correct results.


Comments

Popular posts from this blog

c++ - Is it possible to compile a VST on linux? -

java - Output of Eclipse is rubbish -

jquery - Confused with JSON data and normal data in Django ajax request -