Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
argmin() and argsort()
#1


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
Reply
#2
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?
Reply
#3
you can get the max of a list with:
max(x)
Reply
#4
(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.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#5
(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.
Reply
#6
I understand now.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020