如何进行numpy分区

2024-09-27 04:23:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图弄清楚np.partition函数是如何工作的。 例如,考虑

arr = np.array([ 5, 4, 1, 0, -1, -3, -4, 0])

如果我打电话给np.partition(arr, kth=2),我得到

np.array([-4, -3, -1, 0, 1, 4, 5, 0])

我希望在分区后数组将被拆分为元素少一个,元素大一个。 但是第二个零放在最后一个数组位置,这不是它在分区后的正确位置。在


Tags: 函数元素np数组array分区partitionarr
2条回答

documentation上写着:

Creates a copy of the array with its elements rearranged in such a way that the value of the element in kth position is in the position it would be in a sorted array. All elements smaller than the kth 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.

在您给出的示例中,您选择了已排序列表的第2个元素(从零开始),即-1,如果对数组进行排序,它似乎位于正确的位置。在

The docs talk of 'a sorted array'.

np.partition首先对提供的数组中的元素进行排序。在这种情况下,原始数组是:

arr = [ 5,  4,  1,  0, -1, -3, -4,  0]

分类后,我们有:

^{pr2}$

因此,调用np.partition(arr, kth=2),实际上将kth作为arr_sorted2位置的元素,而不是arr。元素被正确地选为-1。在

相关问题 更多 >

    热门问题