0

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.

1

3 Answers 3

1

You can also have it like

a[np.argmin(a[:, 1])]
Sign up to request clarification or add additional context in comments.

Comments

1

Try with argsort:

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

3 Comments

np.sort(a, axis=0) gives [[ 1, 2], [ 1, 2], [ 1, 2], [ 1, 2], [ 1, 3], [ 2, 3], [ 2, 3], [ 2, 3], [ 2, 3], [ 2, 3], [ 3, 3], [ 3, 3], [ 3, 3], [ 3, 3], [ 4, 3], [ 4, 3], [ 4, 3], [ 4, 4], [ 5, 4], [ 5, 4], [ 5, 4], [ 5, 20]]. Looks like it doesn't preserve the order.
My point is. Your solution just works for just this example. Change a=np.array([[1,20], [2,3], [3,3], [4,3], [5,1],[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]]), which your np.sort(a, axis=0)[0] gives [1, 1] which is not even in a, is it?
@stochasticlearner - Aah, I see what you mean. Apologies, edited
1

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])

2 Comments

since you are slicing twice, will it hurt the performance?
@stochasticlearner edited answer. It's better you consider the first column too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.