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)

学习链接:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值