I am trying to use numpy.argpartition
to get the n
smallest values from an array. However, I cannot guarantee that there will be at least n
values in the array. If there are fewer than n
values, I just need the entire array.
Currently I am handling this with checking the array size, but I feel like I'm missing a native numpy method that will avoid this branching check.
if np.size(arr) < N:
return arr
else:
return arr[np.argpartition(arr, N)][:N]
Minimal reproducible example:
import numpy as np
#Find the 4 smallest values in the array
#Arrays can be arbitrarily sized, as it's the result of finding all elements in a larger array
# that meet a threshold
small_arr = np.array([3,1,4])
large_arr = np.array([3,1,4,5,0,2])
#For large_arr, I can use np.argpartition just fine:
large_idx = np.argpartition(large_arr, 4)
#large_idx now contains array([4, 5, 1, 0, 2, 3])
#small_arr results in an indexing error doing the same thing:
small_idx = np.argpartition(small_arr, 4)
#ValueError: kth(=4) out of bounds (3)
I've looked through the numpy docs for truncation, max length, and other similar terms, but nothing came up that is what I need.