ZR-
ZR-

Reputation: 819

Finding the three largest elements in an array

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!!

Upvotes: 2

Views: 3215

Answers (4)

Nick
Nick

Reputation: 147216

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]

Upvotes: 1

Kuldeep Singh Sidhu
Kuldeep Singh Sidhu

Reputation: 3856

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

Upvotes: 1

Bryan
Bryan

Reputation: 1375

Sort your list:

sorted_list = sorted(pa)

Get the second and third largest value:

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

Upvotes: 1

kmiller96
kmiller96

Reputation: 349

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.

Upvotes: 1

Related Questions