Find Nth Smallest Element In Numpy Array
I need to find just the the smallest nth element in a 1D numpy.array. For example: a = np.array([90,10,30,40,80,70,20,50,60,0]) I want to get 5th smallest element, so my desired
Solution 1:
Unless I am missing something, what you want to do is:
>>>a = np.array([90,10,30,40,80,70,20,50,60,0])>>>np.partition(a, 4)[4]
40
np.partition(a, k)
will place the k
-th smallest element of a
at a[k]
, smaller values in a[:k]
and larger values in a[k+1:]
. The only thing to be aware of is that, because of the 0 indexing, the fifth element is at index 4.
Solution 2:
You can use heapq.nsmallest
:
>>>import numpy as np>>>import heapq>>>>>>a = np.array([90,10,30,40,80,70,20,50,60,0])>>>heapq.nsmallest(5, a)[-1]
40
Solution 3:
you don't need call numpy.max()
:
defnsmall(a, n):
return np.partition(a, n)[n]
Post a Comment for "Find Nth Smallest Element In Numpy Array"