Quantcast
Channel: A fast way to find the largest N elements in an numpy array - Stack Overflow
Viewing all articles
Browse latest Browse all 8

Answer by Akavall for A fast way to find the largest N elements in an numpy array

$
0
0

numpy 1.8 implements partition and argpartition that perform partial sort ( in O(n) time as opposed to full sort that is O(n) * log(n)).

import numpy as nptest = np.array([9,1,3,4,8,7,2,5,6,0])temp = np.argpartition(-test, 4)result_args = temp[:4]temp = np.partition(-test, 4)result = -temp[:4]

Result:

>>> result_argsarray([0, 4, 8, 5]) # indices of highest vals>>> resultarray([9, 8, 6, 7]) # highest vals

Timing:

In [16]: a = np.arange(10000)In [17]: np.random.shuffle(a)In [18]: %timeit np.argsort(a)1000 loops, best of 3: 1.02 ms per loopIn [19]: %timeit np.argpartition(a, 100)10000 loops, best of 3: 139 us per loopIn [20]: %timeit np.argpartition(a, 1000)10000 loops, best of 3: 141 us per loop

Viewing all articles
Browse latest Browse all 8

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>