Python科学计算库NumPy学习笔记(3)--排序与索引

2/22/2017来源:ASP.NET技巧人气:2893

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]

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

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 ]

3.多重复制: .tile

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]]