python - 如何在使用numpy分区排序后获取数组中 float 的索引

标签 python sorting numpy

我试图使用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/

相关文章:

Python Selenium WebDriver 在新版本(2.4.9)中无法执行 quit()

c - 重新排列计算器 BODMAS 的数组

python - 多维 numpy 矩阵的旋转和翻转

mysql - mysql中按频率和自定义表达式排序

python - 如何避免使用opencv和numpy逐像素循环遍历图像

python-3.x - 如何将 4d numpy 数组转换为 PIL 图像?

python - 当 Django 似乎正在搜索正确的路径时如何解决 'TemplateDoesNotExist' 错误

python - Python-Opencv错误:(-215)scn == 3 || scn == 4在函数cv::cvtColor中

pythonanywhere 404错误

python - 如何根据依赖排序?