What is the fastest way to select the smallest n elements from an array?

Viewed 666

I was having fun writing a quick select algorithm using numba and wanted to share the results.

Consider the array x

np.random.seed([3,1415])
x = np.random.permutation(np.arange(10))
x

array([9, 4, 5, 1, 7, 6, 8, 3, 2, 0])

What is the quickest way to pull the smallest n elements.

I've tried
np.partition

np.partition(x, 5)[:5]

array([0, 1, 2, 3, 4])

pd.Series.nsmallest

pd.Series(x).nsmallest(5).values

array([0, 1, 2, 3, 4])
2 Answers
Related