0

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?

5
  • 2
    How is [[1,3],[2,5]] "N maximum values from each array"? And I'd be more concerned with doing it *correctly" than "efficiently". Commented Apr 1, 2022 at 12:23
  • 1
    It's kind of ambiguous what the expected result is, does np.partition(x, -N, axis=1)[:,-N:] give the desired result? Commented Apr 1, 2022 at 12:30
  • @ScottHunter sorry it was my mistake, I have edited it. Commented Apr 1, 2022 at 14:05
  • You got the wrong axis. Commented Apr 1, 2022 at 16:36
  • axis=1 just gives the whole array Commented Apr 1, 2022 at 18:30

1 Answer 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
Sign up to request clarification or add additional context in comments.

2 Comments

This solution works but partition is O(n), sort is O(n * log(n)).
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.