How does numpy's argpartition work on the documentation's example?

后端 未结 3 768
一个人的身影
一个人的身影 2021-02-04 08:11

I am trying to understand numpy\'s argpartition function. I have made the documentation\'s example as basic as possible.

import numpy as np

x = np.array([3, 4,         


        
3条回答
  •  灰色年华
    2021-02-04 08:57

    The more complete answer to what argpartition does is in the documentation of partition, and that one 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. The ordering of the elements in the two partitions is undefined.

    So, for the input array 3, 4, 2, 1, the sorted array would be 1, 2, 3, 4.

    The result of np.partition([3, 4, 2, 1], 3) will have the correct value (i.e. same as sorted array) in the 3rd (i.e. last) element. The correct value for the 3rd element is 4.

    Let me show this for all values of k to make it clear:

    • np.partition([3, 4, 2, 1], 0) - [1, 4, 2, 3]
    • np.partition([3, 4, 2, 1], 1) - [1, 2, 4, 3]
    • np.partition([3, 4, 2, 1], 2) - [1, 2, 3, 4]
    • np.partition([3, 4, 2, 1], 3) - [2, 1, 3, 4]

    In other words: the k-th element of the result is the same as the k-th element of the sorted array. All elements before k are smaller than or equal to that element. All elements after it are greater than or equal to it.

    The same happens with argpartition, except argpartition returns indices which can then be used for form the same result.

提交回复
热议问题