Sort Array and find the n largest value
1. 返回Index:
Sort the whole array
arg sort: 给需要排序的array,返回index值
https://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html#numpy.argsort
In [1]: import numpy as np
In [2]: arr = np.array([1, 3, 2, 4, 5])
In [3]: arr.argsort()[-3:][::-1] ##[::-1] is reverse
Out[3]: array([4, 3, 1])
Array partial sort
useful when deal with large data set, fast
argpartition 用法:
https://docs.scipy.org/doc/numpy/reference/generated/numpy.argpartition.html
注意kth 参数用法:kth: int or sequence of ints
Element index to partition by. The k-th element will be in its final sorted position and all smaller elements will be moved before it and all larger elements behind it. The order all elements in the partitions is undefined. If provided with a sequence of k-th it will partition all of them into their sorted position at once.
取largest 4:
>>> a
array([9, 4, 4, 3, 3, 9, 0, 4, 6, 0])
>>> ind = np.argpartition(a, -4)[-4:]
>>> ind
array([1, 5, 8, 0])
>>> a[ind]
array([4, 9, 6, 9])
这里:给需要排序的array和需要排序的个数,返回index值
2. 返回sort好的array
最简单的按某个列sort:
r.sort(order = 'b')
numpy.ndarray.partition