Hello guest, if you read this it means you are not registered. Click here to register in a few simple steps, you will enjoy all features of our Forum.
Bottom Page

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
Quote
#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?
Quote
#3
you can get the max of a list with:
max(x)
Quote
#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.
My code examples are always for Python 3.x.
All humans together. We don't need politicians!
Quote
#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.
Quote
#6
I understand now.
Quote

Top Page

Forum Jump:


Users browsing this thread: 1 Guest(s)