Home > database >  Finding minimum value of 2d numpy array based on second value of row
Finding minimum value of 2d numpy array based on second value of row

Time:05-11

I have a NumPy array similar to as shown below and I want to find the minimum element based on the second item of the row. I can achieve this using the sorted function, is there a built-in NumPy function to achieve the same (probably the one-liner function)?

import numpy as np
a = np.array([[1,20], [2,3], [3,3], [4,3], [5,4],[1,2], [2,3], [3,3], [4,3], [5,4],[1,2], [2,3], [3,3], [4,3], [5,4], [1,2], [2,3], [3,3], [4,3], [5,4], [1,2], [2,3]])

min_ = sorted(a, key=lambda row: row[1])[0]

Thanks a lot in advance.

CodePudding user response:

You can also have it like

a[np.argmin(a[:, 1])]

CodePudding user response:

Try with argsort:

>>> a[a[:, 1].argsort()][0]
array([1, 2])

CodePudding user response:

You can use numpy.lexsort to sort multiple axes like the below:

>>> a[np.lexsort((a[:,1], a[:,0]))][0]
array([ 1,  2])

In python, sorts are guaranteed to be stable. If you have a value similar to the other values in the second column, maybe you get the wrong answer.

Ref:

Sort Stability and Complex Sorts

Sorts are guaranteed to be stable. That means that when multiple records have the same key, their original order is preserved.

>>> a = np.array([[2,1], [1,1]])
>>> a[np.argmin(a[:, 1])]
array([ 2,  1])

>>> a[a[:, 1].argsort()][0]
array([ 2,  1])

>>> a[np.lexsort((a[:,1], a[:,0]))][0]
array([ 1,  1])
  • Related