网址:https://blog.youkuaiyun.com/jiajing_guo/article/details/62223217
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.youkuaiyun.com/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()
- # 方法一:
- import numpy as np
- a = np.array([[4,3,5,],[1,2,1]])
- print (a)
- b = np.sort(a, axis=1) # 对a按每行中元素从小到大排序
- print (b)
- # 输出 [[4 3 5]
- [1 2 1]]
- [[3 4 5]
- [1 1 2]]
-
- # 方法二:
- import numpy as np
- a = np.array([[4,3,5,],[1,2,1]])
- print (a)
- a.sort(axis=1)
- print (a)
- # 输出 [[4 3 5]
- [1 2 1]]
- [[3 4 5]
- [1 1 2]]
-
- # 方法三:
- import numpy as np
- a = np.array([4, 3, 1, 2])
- b = np.argsort(a) # 求a从小到大排序的坐标
- print (b)
- print (a[b]) # 按求出来的坐标顺序排序
- # 输出 [2 3 1 0]
- [1 2 3 4]
- import numpy as np
- data = np.sin(np.arange(20)).reshape(5, 4)
- print (data)
- ind = data.argmax(axis=0) # 按列得到每一列中最大元素的索引,axis=1为按行
- print (ind)
- data_max = data[ind, range(data.shape[1])] # 将最大值取出来
- print (data_max)
- # 输出 [[ 0. 0.84147098 0.90929743 0.14112001]
- [-0.7568025 -0.95892427 -0.2794155 0.6569866 ]
- [ 0.98935825 0.41211849 -0.54402111 -0.99999021]
- [-0.53657292 0.42016704 0.99060736 0.65028784]
- [-0.28790332 -0.96139749 -0.75098725 0.14987721]]
- [2 0 3 1]
- [ 0.98935825 0.84147098 0.99060736 0.6569866 ]
-
- print data.max(axis=0) #也可以直接取最大值
- # 输出 [ 0.98935825 0.84147098 0.99060736 0.6569866 ]
- import numpy as np
- a = np.array([5, 10, 15])
- print(a)
- print('---')
- b = np.tile(a, (4, 1)) # 参数(4, 1)为按行复制4倍,按列复制1倍
- print(b)
- # 输出 [ 5 10 15]
- ---
- [[ 5 10 15]
- [ 5 10 15]
- [ 5 10 15]
- [ 5 10 15]]
-
- c = np.tile(a, (2, 3)) # 参数(2, 3)为按行复制2倍,按列复制3倍
- print(c)
- # 输出 [[ 5 10 15 5 10 15 5 10 15]
- [ 5 10 15 5 10 15 5 10 15]]
4.两个矩阵对应元素取最小值:minimum()
- import numpy as np
-
- a = array([[21,-12,11],[1,-3,5],[3,4,5]])
- b = array([[11,12,13],[2,3,4],[3,4,5]])
-
- c = minimum(a,b)
-
- >>> c
- array([[ 11, -12, 11],
- [ 1, -3, 4],
- [ 3, 4, 5]])
5.使用Python random模块的choice方法随机选择某个元素
- foo = ['a', 'b', 'c', 'd', 'e']
- from random import choice
- print choice(foo)