十月组队学习之——Numpy(上)Task05 - 排序搜索计数及集合操作

    有幸参加了DataWhale举办的Numpy组队学习。收获颇多。

    每天记录一些自己之前的知识盲点,需经常温习。

13
排序,搜索和计数
13.1
排序

1. numpy.sort(a[, axis=-1, kind='quicksort', order=None]) Return a sorted copy of an array.
a. axis:排序沿数组的(轴)方向,0表示按行,1表示按列,None表示展开来排序,默认为-1,表示沿最后的轴排序。
b. kind:排序的算法,提供了快排'quicksort'、混排'mergesort'、堆排'heapsort', 默认为‘quicksort'。
c. order:排序的字段名,可指定字段排序,默认为None。
【例】

import numpy as np

np.random.seed(20200612)
x = np.random.rand(5, 5) * 10
x = np.around(x, 2)
print(x)
# [[2.32 7.54 9.78 1.73 6.22]
# [6.93 5.17 9.28 9.76 8.25]
# [0.01 4.23 0.19 1.73 9.27]
# [7.99 4.97 0.88 7.32 4.29]
# [9.05 0.07 8.95 7.9 6.99]]
y = np.sort(x)
print(y)
# [[1.73 2.32 6.22 7.54 9.78]
# [5.17 6.93 8.25 9.28 9.76]
# [0.01 0.19 1.73 4.23 9.27]
# [0.88 4.29 4.97 7.32 7.99]
# [0.07 6.99 7.9 8.95 9.05]]
y = np.sort(x, axis=0)
print(y)
# [[0.01 0.07 0.19 1.73 4.29]
# [2.32 4.23 0.88 1.73 6.22]
# [6.93 4.97 8.95 7.32 6.99]
# [7.99 5.17 9.28 7.9 8.25]
# [9.05 7.54 9.78 9.76 9.27]]
y = np.sort(x, axis=1)
print(y)
# [[1.73 2.32 6.22 7.54 9.78]
# [5.17 6.93 8.25 9.28 9.76]
# [0.01 0.19 1.73 4.23 9.27]
# [0.88 4.29 4.97 7.32 7.99]
# [0.07 6.99 35 7.9 8.95 9.05]]

【例】

import numpy as np

dt = np.dtype([('name', 'S10'), ('age', np.int)])
a = np.array([("Mike", 21), ("Nancy", 25), ("Bob", 17), ("Jane", 27)], dtype=dt)
b = np.sort(a, order='name')
print(b)
# [(b'Bob', 17) (b'Jane', 27) (b'Mike', 21) (b'Nancy', 25)]
b = np.sort(a, order='age')
print(b)
# [(b'Bob', 17) (b'Mike', 21) (b'Nancy', 25) (b'Jane', 27)]

如果排序后,想用元素的索引位置替代排序后的实际结果,该怎么办呢?
1. numpy.argsort(a[, axis=-1, kind='quicksort', order=None]) Returns the indices that would sort an array.
【例】对数组沿给定轴执行间接排序,并使用指定排序类型返回数据的索引数组。这个索引数组用于构造排序后的数组。

import numpy as np

np.random.seed(20200612)
x = np.random.randint(0, 10, 10)
print(x)
# [6 1 8 5 5 4 1 2 9 1]
y = np.argsort(x)
print(y)
# [1 6 9 7 5 3 4 0 2 8]
print(x[y])
# [1 1 1 2 4 5 5 6 8 9]
y = np.argsort(-x)
print(y)
# [8 2 0 3 4 5 7 1 6 9]
print(x[y])
# [9 8 6 5 5 4 2 1 1 1]

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值