Numpy array return rows based on criteria

Viewed 28

I would like to return the rows of a numpy array where the second value is larger than the second to last value. For example

[[5 0 3 3] 
 [7 9 3 5] 
 [2 4 7 6] 
 [8 8 1 6]]

would return

[[7 9 3 5]
 [8 8 1 6]]

Thanks!

1 Answers

Create a mask where the 2nd col is greater than 2nd to last col:

mask = a[:,1] > a[:,-2]

# array([False,  True, False,  True])

And index with the mask:

a[mask]

# array([[7, 9, 3, 5],
#        [8, 8, 1, 6]])

This is broken into steps for clarity, but of course you can combine them into one expression a[a[:,1] > a[:,-2]].

Related