找到numpy数组中的n个最小项

the*_*cks 3 python arrays numpy

这里有很多问题,想要找到numpy数组中的第n个最小元素.但是,如果你有一个数组数组怎么办?像这样:

>>> print matrix
[[ 1.          0.28958002  0.09972488 ...,  0.46999924  0.64723113
   0.60217694]
 [ 0.28958002  1.          0.58005657 ...,  0.37668355  0.48852272
   0.3860152 ]
 [ 0.09972488  0.58005657  1.         ...,  0.13151364  0.29539992
   0.03686381]
 ..., 
 [ 0.46999924  0.37668355  0.13151364 ...,  1.          0.50250212
   0.73128971]
 [ 0.64723113  0.48852272  0.29539992 ...,  0.50250212  1.          0.71249226]
 [ 0.60217694  0.3860152   0.03686381 ...,  0.73128971  0.71249226  1.        ]]
Run Code Online (Sandbox Code Playgroud)

如何从这个数组中获取n个最小的项目?

>>> print type(matrix)
<type 'numpy.ndarray'>
Run Code Online (Sandbox Code Playgroud)

这就是我一直在寻找最小项目的坐标:

min_cordinates = []
for i in matrix:
    if numpy.any(numpy.where(i==numpy.amin(matrix))[0]):
        min_cordinates.append(int(numpy.where(i==numpy.amin(matrix))[0][0])+1)
Run Code Online (Sandbox Code Playgroud)

现在我想找到10个最小的项目.

qwr*_*qwr 6

展平矩阵,排序然后选择前10个.

print(numpy.sort(matrix.flatten())[:10])
Run Code Online (Sandbox Code Playgroud)


War*_*ser 6

如果您的阵列不大,接受的答案就可以了.对于大型阵列,np.partition将更有效地实现这一目标.这是一个数组有10000个元素的例子,你想要10个最小的值:

In [56]: np.random.seed(123)

In [57]: a = 10*np.random.rand(100, 100)
Run Code Online (Sandbox Code Playgroud)

使用np.partition得到10个最小值:

In [58]: np.partition(a, 10, axis=None)[:10]
Out[58]: 
array([ 0.00067838,  0.00081888,  0.00124711,  0.00120101,  0.00135942,
        0.00271129,  0.00297489,  0.00489126,  0.00556923,  0.00594738])
Run Code Online (Sandbox Code Playgroud)

请注意,值不按递增顺序排列. np.partition不保证前10个值将被排序.如果按升序需要它们,则可以在之后对所选值进行排序.这仍然比排序整个阵列更快.

这是使用的结果np.sort:

In [59]: np.sort(a, axis=None)[:10]
Out[59]: 
array([ 0.00067838,  0.00081888,  0.00120101,  0.00124711,  0.00135942,
        0.00271129,  0.00297489,  0.00489126,  0.00556923,  0.00594738])
Run Code Online (Sandbox Code Playgroud)

现在比较时间:

In [60]: %timeit np.partition(a, 10, axis=None)[:10]
10000 loops, best of 3: 75.1 µs per loop

In [61]: %timeit np.sort(a, axis=None)[:10]
1000 loops, best of 3: 465 µs per loop
Run Code Online (Sandbox Code Playgroud)

在这种情况下,使用np.partition速度提高了六倍多.