0

If I have the following array: a = [4, -5, 10, 4, 4, 4, 0, 4, 4]

To get the three minimum values index I do:

a1 = np.array(a) 
print a1.argsort()[:3]

This outputs the following, which is ok:

[1 6 0]

The thing is that this includes that -5 (index 1).

How can I do this exact thing but ignoring the -5 of the array?

Avión
  • 7,963
  • 11
  • 64
  • 105
  • 1
    Have you read this: http://stackoverflow.com/questions/7994394/efficient-thresholding-filter-of-an-array-with-numpy – Chris Cooper Oct 24 '14 at 09:54
  • 4
    You want to filter out `-5` specifically, or negative numbers, or the second element of `a`? What is your criterion exactly for excluding `-5`? –  Oct 24 '14 at 10:06
  • Filter out `-5` as I told in the post. Thanks in advance. – Avión Oct 24 '14 at 10:22
  • 1
    you should just do the filtering of unwanted values beforehand ... – eickenberg Oct 24 '14 at 11:34

2 Answers2

2

If you're looking to exclude the minimum element, you can simply skip the element while slicing:

>>> a = [4, 3, 10, -5, 4, 4, 4, 0, 4, 4]
>>> a1 = np.array(a) 
>>> minimum_indexes= a1.argsort()[1:4]
>>> print a1[minimum_indexes]
[0 3 4]
loopbackbee
  • 21,962
  • 10
  • 62
  • 97
  • I need a general solution, for next iteration that -5 can be placed in any other position of the array. Thanks in advance. – Avión Oct 24 '14 at 10:06
  • 2
    @Borja this *is* a general solution - note that you're skipping the first element of the *index array*, not the unsorted one. I've updated the question with a different full example. – loopbackbee Oct 24 '14 at 10:10
  • 2
    @Borja Or did you want to ignore `-5` *specifically*, and not the minimum element? – loopbackbee Oct 24 '14 at 10:12
  • Yes, exactly goncalopp. I want to ignore `-5` specifically as I told in the post. Thanks in advance. – Avión Oct 24 '14 at 10:21
2

You can filter out your specific number after argsort:

>>> a = [4, -5, 10, 4, 4, 4, 0, 4, 4]
>>> a1 = np.array(a) 
>>> indices = a1.argsort()
>>> indices = indices[a1[indices] != -5]
>>> print(indices[:3])
[6 0 3]

It's easy to change your condition. For instance, if you want to filter out all negative numbers, then use the following line instead:

>>> indices = indices[a1[indices] >= 0]