2

I have an array with 4 randomly generated elements (using Python):

pa = np.random.normal(10, 5, 4)

I can find the largest element by doing:

ml = np.max(pa)
mll = np.where(pa == ml)
print(mll)

I'm wondering how can I find the 2nd and 3rd elements in this array? Also, my current output looks like:

(array([0]),)

Is there a way I can get a pure numerical output (0)? Thanks!

Update: Sorry for the previous confusion, I want to find the index of the 2nd and 3rd largest element, but all the answers so far are very helpful to me. Thanks!!

3
  • 1
    Do you want the largest values or the indexes of the largest values? Commented Nov 28, 2020 at 3:58
  • heapq.nlargest? Commented Nov 28, 2020 at 3:59
  • @Nick Thanks for the comment! I want the indexes of the largest values:) Commented Nov 28, 2020 at 4:02

4 Answers 4

1

If you want the three largest of the four values, then you can just find all the values that are greater than the minimum value. You can use argwhere to get just an array of indexes:

import numpy as np

pa = np.random.normal(10, 5, 4)
ml = np.min(pa)
mll = np.argwhere(pa > ml)
print(mll)

Sample output:

[[0]
 [1]
 [3]]

To flatten that output, convert to an array and flatten:

mll = np.array(np.nonzero(pa > ml)).flatten()
print(mll)

Sample output:

[0 1 3]
Sign up to request clarification or add additional context in comments.

Comments

1

If your list is small enough, you can just sort it and grab the last 3 elements of a sorted list.

np.sort(pa)[-3:]

However this will scale badly compared to a more bespoke search algorithm which doesn't care about ordering and only cares about the top 3 elements.

You can convert the array to a list via .tolist(). Any formatting from there is pretty easy to do.

Comments

1

Sort your list:

sorted_list = sorted(pa)

Get the second and third largest value:

print(sorted_list[-2]) and print(sorted_list[-3]).

Comments

1
import numpy as np

arr = np.array([1, 3, 2, 10, 4, 5])

ezAns = arr.argsort()[-3:][::-1] #nlog(n) will give top 3 elements location

ans = np.argpartition(arr, -3)[-3:] #linear time, you will get top 3 elements location but not in order
print(ezAns, ans)

ansVal = np.array([arr[i] for i in ezAns])
print(ansVal)
[3 5 4] [4 5 3] <<Indeces
[10  5  4] <<Values

Some interesting stuff I found: argpartition runs in linear time, O(n), using the introselect algorithm

1 Comment

Thank you so much for your answer! That's really helpful:)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.