0

I have an array of floats and I need to return the index of the N smallest values. What I'm thinking (if there's a better way, please sing out) is to convert the array to an array of tuples where the [0] entry is the original float and the [1] entry is the index in the array.

Then I sort the array by the [0] entries and then for the top N entries, return the [1] value.

So the question is, how can I convert an array of floats to an array of tuples with the [0] entry from the original array. I know how to do this with a for loop, but I'm asking this question to see if numpy has a call that can do this.

David Thielen
  • 28,723
  • 34
  • 119
  • 193
  • 23k rep and no code, sample data, or expected outcome provided... – ddejohn Sep 08 '21 at 19:36
  • A list of index-value tuples: `list(enumerate(float_values))` – ddejohn Sep 08 '21 at 19:37
  • @blorgon I try to explain the question in the best way possible. Sometimes that's sample data and code. But other times it's describe the problem. And I lean toward describe because that more often leads to a better approach. – David Thielen Sep 08 '21 at 20:17

2 Answers2

2

If you would like to get the indices of the N smallest values you can use the argpartition funtion such as:

import numpy as np

N = 3
array = np.array([0.0, 0.1, 0.2, 3.0, 0.4, 0.5, 0.1])
smallest_indices = np.argpartition(array, N)[:N]

So for (say) N = 3 the output would be:

>>> print(smallest_indices)
[1 0 6]

>>> print(array[smallest_indices])
[0.1 0.0 0.1]
  • At least flag this as duplicate instead of copy/pasting answers from other posts. – Chris Sep 08 '21 at 22:21
  • Look: I'm new to this, I saw that your answer while I was writing my reply, I only saw the post you linked after submitting my reply, and then realised that it was a similar solution. If you tell me how to do it I can flag this as duplicate. – Lluis Simon Sep 08 '21 at 22:30
1

You could do it with enumerate and sorted w/a key. Or you can use numpy like in this post.

n = 4
f = [2.0,1.0,3.0,4.0,5.0]
[n[0] for n in sorted([(c,x) for c,x in enumerate(f)], key=lambda x:x[1], reverse=True)[:n]]

Output

[4,3,2,0]
Chris
  • 15,819
  • 3
  • 24
  • 37