2

I didn't understand how numpy.partition works. The documentation says:

Creates a copy of the array with its elements rearranged in such a way that the value of the element in k-th position is in the position it would be in a sorted array. All elements smaller than the k-th element are moved before this element and all equal or greater are moved behind it.

I have tried to run this code

import numpy as np
a = np.array([2, 4, 1, 5, 0])
np.partition(a,0)

The 0-th element of the array is 2, so I would expect the resulting array to be made as following: all elements smaller than 2 to the left of it, and all elements greater than 2 to the right of it.

Instead I get the following result:

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

where 2 is in the last position.

How is this result justified given the documentation?

Can you provide a step-by-step example of what this np.partition does?

Josh Friedlander
  • 10,870
  • 5
  • 35
  • 75
robertspierre
  • 3,218
  • 2
  • 31
  • 46
  • Your interpretation is wrong. Smallest K elements would be in the first K positions in the output, while the rest in the remaining len(array)-K positions. Your statement/interpretation starts with `The 0-th element of the array is 2,..`, which sounds like you are trying to do something else. – Divakar Jun 02 '20 at 10:57
  • @Divakar thank you. Can you provide an example of how does the function works? The documentation says "the element in the k-th position", what is the correct interpretation? – robertspierre Jun 02 '20 at 11:01
  • It's right there. `Creates a copy of the array with its elements rearranged in such a way that the value of the element in k-th position`. They are talking about the `k-th position` in the **output, not the input**. – Divakar Jun 02 '20 at 11:07
  • 1
    Can I have in a reply a step-by-step example of what this function does, please? – robertspierre Jun 02 '20 at 11:29
  • The key is that ``k`` refers to the ``k``th element *after partitioning*. – MisterMiyagi Jun 02 '20 at 11:40
  • This did a good job on it - https://stackoverflow.com/a/61194012/. – Divakar Jun 02 '20 at 11:59

0 Answers0