'How to get N maximum values of each array from a numpy array of arrays
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?
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ali_Sh |
