I have a numpy array of arrays x = [[1, 3, 4, 5], [6, 2, 5, 7]]. I want to get N maximum values from each array of the numpy array: [[5, 4], [7, 6]]. I have tried using np.argpartition(x, -N, axis=0)[-N:] but it gives ValueError: kth(=-3) out of bounds (1). What is the efficient way for doing this?
1 Answer
You can do this by sorting each row and slicing as you want:
np.sort(x, axis=1)[:, :2] # --> [[1 3] [2 5]] 2 minimum in each row
np.sort(x, axis=1)[:, 2:] # --> [[4 5] [6 7]] 2 maximum in each row
2 Comments
Michael Szczesny
This solution works but
partition is O(n), sort is O(n * log(n)).Ali_Sh
@MichaelSzczesny, I agree. I saw
partition is corrected by your comment; So, I didn't write that in my answer. Also, the author didn't emphasize on using just partition to solve the problem. Again, partition is the better choice.
[[1,3],[2,5]]"N maximum values from each array"? And I'd be more concerned with doing it *correctly" than "efficiently".np.partition(x, -N, axis=1)[:,-N:]give the desired result?