Numpy讲堂:排序及返回索引、多重复制、两个矩阵对应元素取最小值、随机选择元素

				网址:https://blog.csdn.net/jiajing_guo/article/details/62223217
				版权声明:本文为博主原创文章,未经博主允许不得转载。					https://blog.csdn.net/Jiajing_Guo/article/details/62223217				</div>
							            <link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/ck_htmledit_views-db05db230f.css">
					<div class="htmledit_views" id="content_views">

1.排序: sort()


 
 
  1. # 方法一:
  2. import numpy as np
  3. a = np.array([[ 4, 3, 5,],[ 1, 2, 1]])
  4. print (a)
  5. b = np.sort(a, axis= 1) # 对a按每行中元素从小到大排序
  6. print (b)
  7. # 输出 [[4 3 5]
  8. [ 1 2 1]]
  9. [[ 3 4 5]
  10. [ 1 1 2]]
  11. # 方法二:
  12. import numpy as np
  13. a = np.array([[ 4, 3, 5,],[ 1, 2, 1]])
  14. print (a)
  15. a.sort(axis= 1)
  16. print (a)
  17. # 输出 [[4 3 5]
  18. [ 1 2 1]]
  19. [[ 3 4 5]
  20. [ 1 1 2]]
  21. # 方法三:
  22. import numpy as np
  23. a = np.array([ 4, 3, 1, 2])
  24. b = np.argsort(a) # 求a从小到大排序的坐标
  25. print (b)
  26. print (a[b]) # 按求出来的坐标顺序排序
  27. # 输出 [2 3 1 0]
  28. [ 1 2 3 4]


2.按行或按列找到最大值的索引:argmax()


 
 
  1. import numpy as np
  2. data = np.sin(np.arange( 20)).reshape( 5, 4)
  3. print (data)
  4. ind = data.argmax(axis= 0) # 按列得到每一列中最大元素的索引,axis=1为按行
  5. print (ind)
  6. data_max = data[ind, range(data.shape[ 1])] # 将最大值取出来
  7. print (data_max)
  8. # 输出 [[ 0. 0.84147098 0.90929743 0.14112001]
  9. [ -0.7568025 -0.95892427 -0.2794155 0.6569866 ]
  10. [ 0.98935825 0.41211849 -0.54402111 -0.99999021]
  11. [ -0.53657292 0.42016704 0.99060736 0.65028784]
  12. [ -0.28790332 -0.96139749 -0.75098725 0.14987721]]
  13. [ 2 0 3 1]
  14. [ 0.98935825 0.84147098 0.99060736 0.6569866 ]
  15. print data.max(axis= 0) #也可以直接取最大值
  16. # 输出 [ 0.98935825 0.84147098 0.99060736 0.6569866 ]


3.多重复制:tile()


 
 
  1. import numpy as np
  2. a = np.array([ 5, 10, 15])
  3. print(a)
  4. print( '---')
  5. b = np.tile(a, ( 4, 1)) # 参数(4, 1)为按行复制4倍,按列复制1倍
  6. print(b)
  7. # 输出 [ 5 10 15]
  8. ---
  9. [[ 5 10 15]
  10. [ 5 10 15]
  11. [ 5 10 15]
  12. [ 5 10 15]]
  13. c = np.tile(a, ( 2, 3)) # 参数(2, 3)为按行复制2倍,按列复制3倍
  14. print(c)
  15. # 输出 [[ 5 10 15 5 10 15 5 10 15]
  16. [ 5 10 15 5 10 15 5 10 15]]


4.两个矩阵对应元素取最小值:minimum()


 
 
  1. import numpy as np
  2. a = array([[ 21, -12, 11],[ 1, -3, 5],[ 3, 4, 5]])
  3. b = array([[ 11, 12, 13],[ 2, 3, 4],[ 3, 4, 5]])
  4. c = minimum(a,b)
  5. >>> c
  6. array([[ 11, -12, 11],
  7. [ 1, -3, 4],
  8. [ 3, 4, 5]])

5.使用Python random模块的choice方法随机选择某个元素


 
 
  1. foo = [ 'a', 'b', 'c', 'd', 'e']
  2. from random import choice
  3. print choice(foo)




  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值