Adam Toth
Adam Toth

Reputation: 951

Lexicographic comparison of two numpy ndarrays

I couldn't find a straightforward way to compare two (multidimensional in my case) arrays the in a lexicographic way.

Ie.

a = [1,2,3,4]
b = [4,0,1,6]

For a < b I want to get true where I get [true, false, false, true]
For a > b I want to get false where I get [false, true, true, false]

Upvotes: 6

Views: 1399

Answers (2)

Rahul
Rahul

Reputation: 512

If the question is just about finding whether a is < or > than b, then the following should work.

def fn(a, b):
    # finds index of the first non matching element
    idx = np.where( (a>b) != (a<b) )[0][0]

    if a[idx] < b[idx]: print "a < b" 
    if a[idx] > b[idx]: print "a > b" 

Upvotes: 6

Eelco Hoogendoorn
Eelco Hoogendoorn

Reputation: 10759

Multiply with np.arange(4)[::-1] ** 2 and then sum over that axis.

Upvotes: 1

Related Questions