[Numpy-discussion] Using np.partition to extract n largest/smallest items from an array

Jaime Fernández del Río jaime.frio at gmail.com
Fri Dec 13 02:07:28 EST 2013


With the new np.partition functionality, there is a more efficient, but
also less obvious, way of extracting the n largest (or smallest) elements
from an array, i.e.:

def smallest_n(a, n):
    return np.sort(np.partition(a, n)[:n])

def argsmallest_n(a, n):
    ret = np.argpartition(a, n)[:n]
    b = np.take(a, ret)
    return np.take(ret, np.argsort(b))

instead of the usual:

np.sort(a)[:n]
np.argsort(a)[:n]

Are those 4 functions (smallest, argsmallest, largest, arglargest), with
adequate axis support, worthy of including in numpy, or is the name space
already too cluttered?

Jaime

-- 
(\__/)
( O.o)
( > <) Este es Conejo. Copia a Conejo en tu firma y ayúdale en sus planes
de dominación mundial.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20131212/96984829/attachment.html>


More information about the NumPy-Discussion mailing list