Python numpy进行排序【从大到小】和【从小到大】

1 numpy.sort【从小到大】

返回排序后的数组从小到大

numpy.sort(a, axis=-1, kind=None, order=None)
axis:Axis along which to sort. If None, the array is flattened before sorting. The default is -1, which sorts along the last axis.
选择排序的轴,如果没有,将数组铺平
a = np.array([[1,4],[3,1]])
# sort along the last axis,对行进行排序,等于axis=1
np.sort(a)                
array([[1, 4],[1, 3]])
# 将数组铺平
np.sort(a, axis=None)
array([1, 1, 3, 4])
# sort along the first axis,对列进行排序, axis=0
np.sort(a, axis=0)    
array([[1, 1],[3, 4]])

2 numpy.argsort【从小到大】

返回排序后的数组的索引从小到大

numpy.argsort(a, axis=-1, kind=None, order=None)[source]
axis:Axis along which to sort. The default is -1 (the last axis). If None, the flattened array is used.
x = np.array([3, 1, 2])
# 得到索引
np.argsort(x)
array([1, 2, 0])
# 对于二维数组
x = np.array([[0, 3], [2, 2]])
ind = np.argsort(x, axis=0)  # sorts along first axis (down)
ind
array([[0, 1],[1, 0]])
# 利用索引得到排序后的结果
np.take_along_axis(x, ind, axis=0)
array([[0, 2], [2, 3]])

3 numpy.take_along_axis

通过数组的索引得到数组

numpy.take_along_axis(arr, indices, axis)

np.argsort()np.take_along_axis()np.flip()配合使用能够实现数组的【从小到大】或者【从大到小】的排序

# 从大到小
index = np.argsort(data)
index_flip = np.flip(index)
data_sort = np.take_along_axis(index_flip)
# 从小到大
index = np.argsort(data)
data_sort = np.take_along_axis(index)

学习链接:

  • numpy.sort
  • numpy.argsort
  • numpy.take_along_axis

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
xiaoxingxing的头像xiaoxingxing管理团队
上一篇 2023年11月9日
下一篇 2023年11月9日

相关推荐