Python Forum
argmin() and argsort() - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Data Science (https://python-forum.io/forum-44.html)
+--- Thread: argmin() and argsort() (/thread-6271.html)



argmin() and argsort() - PythonNewbie - Nov-13-2017



Hi,

I implemented an algorithm in which I used the argmin() where the index of the smallest number in an array is returned to be used. Now, I would like to generalize my algorithm, and thus I want to return the indices of the smallest k numbers. So, I restored to argsort()[:k]. When I tested it for k = 1, I expected to get the same results as with argmin(), which wasn't the case. I noticed that argsort()[:1] returns an array, while argmin() returns a scalar. Could this be the issue? If not, what else could be?

Thanks


RE: argmin() and argsort() - PythonNewbie - Nov-13-2017

I think it has to do with what argsort() returns. For example,

import numpy as np

k = 1

x = np.array([0, 1, -1, 4, 2])
y = np.array(['a', 'b', 'c', 'd', 'e'])

indx_argmin = x.argmin()
indx_argsort = x.argsort()[:k]

print(indx_argmin, y[indx_argmin])
print(indx_argsort, y[indx_argsort])
outputs

Output:
2 c [2] ['c']
Apparently they are not the same.

How to use argsort() or any other method to obtain the same results as argmin() when k = 1?


RE: argmin() and argsort() - Larz60+ - Nov-13-2017

you can get the max of a list with:
max(x)



RE: argmin() and argsort() - DeaD_EyE - Nov-13-2017

(Nov-13-2017, 10:16 AM)PythonNewbie Wrote: I noticed that argsort()[:1] returns an array, while argmin() returns a scalar.

indx_argmin() returns an integer.
x.argsort() returns an array and then you're accessing a slice with [:k] which still returns an array.


RE: argmin() and argsort() - PythonNewbie - Nov-14-2017

(Nov-13-2017, 07:13 PM)DeaD_EyE Wrote:
(Nov-13-2017, 10:16 AM)PythonNewbie Wrote: I noticed that argsort()[:1] returns an array, while argmin() returns a scalar.

indx_argmin() returns an integer.
x.argsort() returns an array and then you're accessing a slice with [:k] which still returns an array.

Right, but what I am trying to do is select the indices of the k smallest numbers instead of the index of the smallest number as a generalization. I wanted to test the general function argsort()[:k] by putting k = 1 and compare the results to that of argmin(), but the results were different. Why? and how can I fix it?

(Nov-13-2017, 05:46 PM)Larz60+ Wrote: you can get the max of a list with:
max(x)

But I don't want the max of a list. I want the indices of the k smallest numbers in an array.


RE: argmin() and argsort() - Larz60+ - Nov-14-2017

I understand now.