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?

4
  • 1
    Have you read this: stackoverflow.com/questions/7994394/… Commented Oct 24, 2014 at 9: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? Commented Oct 24, 2014 at 10:06
  • Filter out -5 as I told in the post. Thanks in advance. Commented Oct 24, 2014 at 10:22
  • 1
    you should just do the filtering of unwanted values beforehand ... Commented Oct 24, 2014 at 11:34

2 Answers 2

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]
Sign up to request clarification or add additional context in comments.

Comments

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]

4 Comments

I need a general solution, for next iteration that -5 can be placed in any other position of the array. Thanks in advance.
@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.
@Borja Or did you want to ignore -5 specifically, and not the minimum element?
Yes, exactly goncalopp. I want to ignore -5 specifically as I told in the post. Thanks in advance.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.