自其他答案以来,NumPy 添加了numpy.partition http://docs.scipy.org/doc/numpy/reference/generated/numpy.partition.html and numpy.argpartition http://docs.scipy.org/doc/numpy/reference/generated/numpy.argpartition.html部分排序的函数,允许您在O(arr.size)
时间,或O(arr.size+n*log(n))
如果您需要按排序顺序排列的元素。
numpy.partition(arr, n)
返回一个大小为的数组arr
哪里的n
如果数组已排序,则第一个元素就是该元素。所有较小的元素都位于该元素之前,所有较大的元素都位于该元素之后。
numpy.argpartition
is to numpy.partition
as numpy.argsort
is to numpy.sort
.
以下是如何使用这些函数来查找最小值的索引n
二维的元素arr
:
flat_indices = numpy.argpartition(arr.ravel(), n-1)[:n]
row_indices, col_indices = numpy.unravel_index(flat_indices, arr.shape)
如果您需要按顺序排列索引,那么row_indices[0]
是最小元素的行,而不仅仅是其中之一n
最小元素:
min_elements = arr[row_indices, col_indices]
min_elements_order = numpy.argsort(min_elements)
row_indices, col_indices = row_indices[min_elements_order], col_indices[min_elements_order]
一维情况要简单得多:
# Unordered:
indices = numpy.argpartition(arr, n-1)[:n]
# Extra code if you need the indices in order:
min_elements = arr[indices]
min_elements_order = numpy.argsort(min_elements)
ordered_indices = indices[min_elements_order]