我试图使用np.partition
对数组列表进行排序,但它对列表进行了错误的排序。我认为原因是列表中的 float 。如何使用 np.partition
对包含 float 的数组列表进行排序并获取元素的索引?
x = np.array([0.056669, 0.019477, 0.06245, 0., 0.019524, 0.058592, 0.05847, 0.078317, 0.09599])
print(np.partition(x, 1)[0:9])
结果在这里:
[ 0. 0.019477 0.06245 0.056669 0.019524 0.058592 0.05847
0.078317 0.09599 ]
所需的输出在这里:
[3 1 4 0 6 5 2 7 8]
最佳答案
np.partition
只是“分区”你的元素,它并没有进行完整的排序。它用于“获取最低/最高 k
元素”之类的操作。来自文档:
numpy.partition(a, kth, axis=-1, kind='introselect', order=None)
Return a partitioned copy of an array.
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.
如果您想对整个数组进行排序
,您应该使用 np.sort
.
有几个 numpy 函数可以为您提供索引而不是值,这些函数通常以 arg* 开头,例如 np.argsort
.
>>> import numpy as np
>>> arr = np.array([0.056669, 0.019477, 0.06245, 0., 0.019524, 0.058592, 0.05847, 0.078317, 0.09599])
>>> np.partition(arr, 1)
array([ 0. , 0.019477, 0.06245 , 0.056669, 0.019524, 0.058592,
0.05847 , 0.078317, 0.09599 ])
>>> np.argpartition(arr, 1)
array([3, 1, 2, 0, 4, 5, 6, 7, 8], dtype=int64)
>>> np.partition(arr, 7)
array([ 0. , 0.019524, 0.019477, 0.056669, 0.058592, 0.05847 ,
0.06245 , 0.078317, 0.09599 ])
>>> np.argpartition(arr, 7)
array([3, 4, 1, 0, 5, 6, 2, 7, 8], dtype=int64)
>>> np.sort(arr)
array([ 0. , 0.019477, 0.019524, 0.056669, 0.05847 , 0.058592,
0.06245 , 0.078317, 0.09599 ])
>>> np.argsort(arr)
array([3, 1, 4, 0, 6, 5, 2, 7, 8], dtype=int64)
关于python - 如何在使用numpy分区排序后获取数组中 float 的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44021004/