Numpy入门教程:06. 排序,搜索和计数

news/2024/7/7 19:08:54

背景

什么是 NumPy 呢?

NumPy 这个词来源于两个单词 – NumericalPython。其是一个功能强大的 Python 库,可以帮助程序员轻松地进行数值计算,通常应用于以下场景:

  • 执行各种数学任务,如:数值积分、微分、内插、外推等。因此,当涉及到数学任务时,它形成了一种基于 Python 的 MATLAB 的快速替代。
  • 计算机中的图像表示为多维数字数组。NumPy 提供了一些优秀的库函数来快速处理图像。例如,镜像图像、按特定角度旋转图像等。
  • 在编写机器学习算法时,需要对矩阵进行各种数值计算。如:矩阵乘法、求逆、换位、加法等。NumPy 数组用于存储训练数据和机器学习模型的参数。

排序,搜索和计数

排序

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

【例】

import numpy as npnp.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 7.9  8.95 9.05]]

【例】

import numpy as npdt = 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)]

如果排序后,想用元素的索引位置替代排序后的实际结果,该怎么办呢?

  • numpy.argsort(a[, axis=-1, kind='quicksort', order=None]) Returns the indices that would sort an array.

【例】对数组沿给定轴执行间接排序,并使用指定排序类型返回数据的索引数组。这个索引数组用于构造排序后的数组。

import numpy as npnp.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]

【例】

import numpy as npnp.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.argsort(x)
print(y)
# [[3 0 4 1 2]
#  [1 0 4 2 3]
#  [0 2 3 1 4]
#  [2 4 1 3 0]
#  [1 4 3 2 0]]y = np.argsort(x, axis=0)
print(y)
# [[2 4 2 0 3]
#  [0 2 3 2 0]
#  [1 3 4 3 4]
#  [3 1 1 4 1]
#  [4 0 0 1 2]]y = np.argsort(x, axis=1)
print(y)
# [[3 0 4 1 2]
#  [1 0 4 2 3]
#  [0 2 3 1 4]
#  [2 4 1 3 0]
#  [1 4 3 2 0]]y = np.array([np.take(x[i], np.argsort(x[i])) for i in range(5)])
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]]

如何将数据按照某一指标进行排序呢?

  • numpy.lexsort(keys[, axis=-1]) Perform an indirect stable sort using a sequence of keys.

【例】按照第一列的升序或者降序对整体数据进行排序。

import numpy as npnp.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]]index = np.lexsort([x[:, 0]])
print(index)
# [2 0 1 3 4]y = x[index]
print(y)
# [[0.01 4.23 0.19 1.73 9.27]
#  [2.32 7.54 9.78 1.73 6.22]
#  [6.93 5.17 9.28 9.76 8.25]
#  [7.99 4.97 0.88 7.32 4.29]
#  [9.05 0.07 8.95 7.9  6.99]]index = np.lexsort([-1 * x[:, 0]])
print(index)
# [4 3 1 0 2]y = x[index]
print(y)
# [[9.05 0.07 8.95 7.9  6.99]
#  [7.99 4.97 0.88 7.32 4.29]
#  [6.93 5.17 9.28 9.76 8.25]
#  [2.32 7.54 9.78 1.73 6.22]
#  [0.01 4.23 0.19 1.73 9.27]]

【例】

import numpy as npx = np.array([1, 5, 1, 4, 3, 4, 4])
y = np.array([9, 4, 0, 4, 0, 2, 1])
a = np.lexsort([x])
b = np.lexsort([y])
print(a)
# [0 2 4 3 5 6 1]
print(x[a])
# [1 1 3 4 4 4 5]print(b)
# [2 4 6 5 1 3 0]
print(y[b])
# [0 0 1 2 4 4 9]z = np.lexsort([y, x])
print(z)
# [2 0 4 6 5 3 1]
print(x[z])
# [1 1 3 4 4 4 5]z = np.lexsort([x, y])
print(z)
# [2 4 6 5 3 1 0]
print(y[z])
# [0 0 1 2 4 4 9]

搜索

  • numpy.argmax(a[, axis=None, out=None])Returns the indices of the maximum values along an axis.

【例】

import numpy as npnp.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.argmax(x)
print(y)  # 2y = np.argmax(x, axis=0)
print(y)
# [4 0 0 1 2]y = np.argmax(x, axis=1)
print(y)
# [2 3 4 0 0]
  • numpy.argmin(a[, axis=None, out=None])Returns the indices of the minimum values along an axis.

【例】

import numpy as npnp.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.argmin(x)
print(y)  # 10y = np.argmin(x, axis=0)
print(y)
# [2 4 2 0 3]y = np.argmin(x, axis=1)
print(y)
# [3 1 0 2 1]
  • numpy.where(condition, [x=None, y=None]) 函数返回输入数组中满足给定条件的元素的索引。

【例】

import numpy as npx = np.array([1, 2, 3, 4, 5, 6, 7, 8])
y = np.where(x > 5)
print(y)
# (array([5, 6, 7], dtype=int64),)
print(x[y])
# [6 7 8]x = np.array([[11, 12, 13, 14, 15],[16, 17, 18, 19, 20],[21, 22, 23, 24, 25],[26, 27, 28, 29, 30],[31, 32, 33, 34, 35]])
y = np.where(x > 25)
print(y)
# (array([3, 3, 3, 3, 3, 4, 4, 4, 4, 4], dtype=int64), array([0, 1, 2, 3, 4, 0, 1, 2, 3, 4], dtype=int64))print(x[y])
# [26 27 28 29 30 31 32 33 34 35]
  • numpy.searchsorted(a, v[, side='left', sorter=None]) Find indices where elements should be inserted to maintain order.
    • a:一维输入数组。当sorter参数为None的时候,a必须为升序数组;否则,sorter不能为空,存放a中元素的index,用于反映a数组的升序排列方式。
    • v:插入a数组的值,可以为单个元素,list或者ndarray
    • side:查询方向,当为left时,将返回第一个符合条件的元素下标;当为right时,将返回最后一个符合条件的元素下标。
    • sorter:一维数组存放a数组元素的 index,index 对应元素为升序。

【例】

import numpy as npx = np.array([0, 1, 5, 9, 11, 18, 26, 33])
y = np.searchsorted(x, 15)
print(y)  # 5y = np.searchsorted(x, 15, side='right')
print(y)  # 5y = np.searchsorted(x, -1)
print(y)  # 0y = np.searchsorted(x, -1, side='right')
print(y)  # 0y = np.searchsorted(x, 35)
print(y)  # 8y = np.searchsorted(x, 35, side='right')
print(y)  # 8y = np.searchsorted(x, 11)
print(y)  # 4y = np.searchsorted(x, 11, side='right')
print(y)  # 5y = np.searchsorted(x, 0)
print(y)  # 0y = np.searchsorted(x, 0, side='right')
print(y)  # 1y = np.searchsorted(x, 33)
print(y)  # 7y = np.searchsorted(x, 33, side='right')
print(y)  # 8

【例】

import numpy as npx = np.array([0, 1, 5, 9, 11, 18, 26, 33])
y = np.searchsorted(x, [-1, 0, 11, 15, 33, 35])
print(y)  # [0 0 4 5 7 8]y = np.searchsorted(x, [-1, 0, 11, 15, 33, 35], side='right')
print(y)  # [0 1 5 5 8 8]

【例】

import numpy as npx = np.array([0, 1, 5, 9, 11, 18, 26, 33])
np.random.shuffle(x)
print(x)  # [33  1  9 18 11 26  0  5]x_sort = np.argsort(x)
print(x_sort)  # [6 1 7 2 4 3 5 0]y = np.searchsorted(x, [-1, 0, 11, 15, 33, 35], sorter=x_sort)
print(y)  # [0 0 4 5 7 8]y = np.searchsorted(x, [-1, 0, 11, 15, 33, 35], side='right', sorter=x_sort)
print(y)  # [0 1 5 5 8 8]

计数

  • numpy.count_nonzero(a, axis=None) Counts the number of non-zero values in the array a.

【例】返回数组中的非0元素个数。

import numpy as npx = np.count_nonzero(np.eye(4))
print(x)  # 4x = np.count_nonzero([[0, 1, 7, 0, 0], [3, 0, 0, 2, 19]])
print(x)  # 5x = np.count_nonzero([[0, 1, 7, 0, 0], [3, 0, 0, 2, 19]], axis=0)
print(x)  # [1 1 1 1 1]x = np.count_nonzero([[0, 1, 7, 0, 0], [3, 0, 0, 2, 19]], axis=1)
print(x)  # [2 3]

当前活动


我是 终身学习者“老马”,一个长期践行“结伴式学习”理念的 中年大叔

我崇尚分享,渴望成长,于2010年创立了“LSGO软件技术团队”,并加入了国内著名的开源组织“Datawhale”,也是“Dre@mtech”、“智能机器人研究中心”和“大数据与哲学社会科学实验室”的一员。

愿我们一起学习,一起进步,相互陪伴,共同成长。

后台回复「搜搜搜」,随机获取电子资源!
欢迎关注,请扫描二维码:


http://lihuaxi.xjx100.cn/news/254274.html

相关文章

设置列表字段为主键

转贴:Sample event handler to set a field as a pr imary key (enforce no duplicates) Got this as a request from a reader- how to prevent users from adding items with same titles as ones that already exist in the list. Codeusing System;using System.Collectio…

Largest Rectangle in a Histogram

ps&#xff1a;单调栈&#xff0c;注意红色部分的代码。 int n;stack<P> s;inline void upd(LL &x, LL y) { (x < y) && (x y); }int main() {while(sc(n) ! EOF && n) {while(!s.empty()) s.pop();LL ans 0;Rep(i, 1, n) {int x;sc(x);if (s.e…

AI大神LeCun深度学习公开课来啦!4万字干货笔记

Datawhale干货 主讲&#xff1a;Yann LeCun&#xff0c;整理&#xff1a;新智元【新智元导读】Yann LeCun大师课程&#xff0c;搭配120页笔记食用效果更佳。喜欢深度学习&#xff1f;最好的方法就是在线课程。这里推荐图灵奖得主、纽约大学教授Yann LeCun主讲的在线课程。该课程…

云淘金时代,安全为王

在数字经济和技术生态高质量发展的今天&#xff0c;企业对前沿技术和高质量人才的需求不断升级。为了帮助更多开发者、企业洞察行业趋势、技术热点&#xff0c;CSDN 重磅打造技术访谈金牌栏目《架构师说》&#xff0c;聚焦数字化转型、云原生、数据库、开源技术、人工智能、出海…

Nginx 面试 40 连问,快顶不住了~~

欢迎关注方志朋的博客&#xff0c;回复”666“获面试宝典什么是Nginx&#xff1f;Nginx是一个 轻量级/高性能的反向代理Web服务器&#xff0c;用于 HTTP、HTTPS、SMTP、POP3 和 IMAP 协议。他实现非常高效的反向代理、负载平衡&#xff0c;他可以处理2-3万并发连接数&#xff0…

学好计算机第一步

Datawhale干货 作者&#xff1a;cxuan审校&#xff1a;黄元帅前 言计算机已经发展了半个世纪之久&#xff0c;我们从一出生就能享用计算机高速发展的成果&#xff0c;但我们从未对计算机产生过敬畏之心&#xff0c;为什么&#xff1f;因为我们不了解计算机&#xff0c;何谈敬畏…

linux tar的使用方法

tar [-cxtzjvfpPN] 文件与目录 ....参数&#xff1a;-c &#xff1a;建立一个压缩文件的参数指令(create 的意思)&#xff1b;-x &#xff1a;解开一个压缩文件的参数指令&#xff01;-t &#xff1a;查看 tarfile 里面的文件&#xff01;特别注意&#xff0c;在参数的下达中&a…

HDU 4467 分块

题目链接&#xff1a;http://acm.hdu.edu.cn/showproblem.php?pid4467 题意&#xff1a;给定n个点m条边的无向图&#xff0c;点被染色(黑0/白1)&#xff0c;边带边权。然后q个询问。询问分为两种&#xff1a; Change u:把点u的颜色反转(黑变白&#xff0c;白变黑)&#xff0c;…