当前位置:网站首页>numpy.where() 用法和np.argsort()的用法
numpy.where() 用法和np.argsort()的用法
2022-07-29 00:34:00 【51CTO】
numpy.where() 有两种用法:
1. np.where(condition, x, y)
满足条件(condition),输出x,不满足输出y。
如果是一维数组,相当于[xv if c else yv for (c,xv,yv) in zip(condition,x,y)]
上面这个例子的条件为[[True,False], [True,False]],分别对应最后输出结果的四个值。第一个值从[1,9]中选,因为条件为True,所以是选1。第二个值从[2,8]中选,因为条件为False,所以选8,后面以此类推。类似的问题可以再看个例子:
2. np.where(condition)
只有条件 (condition),没有x和y,则输出满足条件 (即非0) 元素的坐标 (等价于 numpy.nonzero)。这里的坐标以tuple的形式给出,通常原数组有多少维,输出的tuple中就包含几个数组,分别对应符合条件元素的各维坐标。
上面这个例子条件中[[0,1],[1,0]]的真值为两个1,各自的第一维坐标为[0,1],第二维坐标为[1,0] 。
下面看个复杂点的例子:
所以np.where会输出每个元素的对应的坐标,因为原数组有三维,所以tuple中有三个数组。
需要注意的一点是,输入的不能直接是list,需要转为array或者为array才行。比如range(10)和np.arange(10)后者返回的是数组,使用np.where才能达到效果。
np.argsort()的用法
argsort(a)#获取a从小到大排列的数组
argsort(-a)#获取a从大到小排列的数组
argmin(a)#获取a最小值下标
argmax(a)#获取a最大值下标
功能: 将矩阵a按照axis排序,并返回排序后的下标
参数: a:输入矩阵, axis:需要排序的维度
返回值: 输出排序后的下标
(一维数组)
可以发现,argsort()是将X中的元素从小到大排序后,提取对应的索引index,然后输出到y
如x[3]=-1最小,x[5]=9最大
所以取数组x的最小值可以写成:
或者用argmin()函数
数组x的最大值,写成:
或者用argmax()函数,不再详述
输出排序后的数组
(二维数组)
沿着列向右(每行)的元素进行排序
作者:你的雷哥
本文版权归作者所有,欢迎转载,但未经作者同意必须在文章页面给出原文连接,否则保留追究法律责任的权利。
边栏推荐
- Bracket matching test
- 一文搞懂ES6基本全部语法
- The solution to keep the height of the container unchanged during the scaling process of the uniapp movable view table
- RHCE command practice (I)
- Tupu software appeared at the 2022 Fuzhou digital Expo to jointly create a new digital era
- 20220728-不纯为数字的字符串排序
- Django uses pymysql module to connect mysql database
- 20220728 sorting strings that are not pure numbers
- 写作作业一
- Behind the second round of okaleido tiger sales is the strategic support of ecological institutions
猜你喜欢

一篇万字博文带你入坑爬虫这条不归路 【万字图文】

Flink Postgres CDC

嵌入式分享合集23

After understanding the composition of the URL of the website, we use the URL module, querystring module and mime module to improve the static website

面试官:程序员,请你告诉我是谁把公司面试题泄露给你的?

Third party login process of flask Weibo

Flask reports an error: pymysq1.err OperationalError:(1054, “Unknown column ‘None‘ in ‘field list‘“)

Recommended Spanish translation of Beijing passport

2022年最火的十大测试工具,你掌握了几个

地下水、土壤、地质、环境人看过来
随机推荐
2022年最火的十大测试工具,你掌握了几个
Openpyxl library fill color
【idea】查询字段使用位置
Subtotal of process thread coordination
Third party login process of flask Weibo
PlatoFarm社区生态福音,用户可借助Elephant Swap获得溢价收益
PLATO上线LAAS协议Elephant Swap,用户可借此获得溢价收益
DocuWare 移动劳动力解决方案可帮助您构建新的生产力模式:随时随地、任何设备
【HCIP】MGRE环境下OSPF实验,含多进程双向重发布及OSPF特殊区域
Flask generates image verification code
els 到底停止
PLATO上线LAAS协议Elephant Swap,用户可借此获得溢价收益
Intel带你初识视觉识别--OpenVINO
一篇万字博文带你入坑爬虫这条不归路 【万字图文】
Synchronized keyword details
RHCE命令练习(二)
Redis is installed on Linux
Flink SQL Hudi actual combat
20220728 sorting strings that are not pure numbers
Behind the second round of okaleido tiger sales is the strategic support of ecological institutions