import numpy as np ‘‘‘ a = np.array([1,2,3]) print(a) print(type(a)) print(a.dtype) # 几行 print(a.ndim) print(a.size) print(a.shape) print(a.data) ‘‘‘ ‘‘‘ a = np.array([[1,2,3],[4,5,6]]) b = np.array(((1,2,3),(4,5,6))) c = np.array([(1,2,3),(4,5,6)]) print(a) print(b) print(c) print(np.zeros((3,3))) print(np.ones((3,3))) print(np.arange(4,10)) print(np.arange(4,10,3)) print(np.arange(4,10,0.5)) # 开头和结尾所指定范围分成多少部分 print(np.linspace(0,10,5)) ‘‘‘ ‘‘‘ A = np.arange(0,9).reshape(3,3) print(A) print(A+4) print(A*2) print(np.sin(A)) print(np.sqrt(A)) B = np.arange(12,21).reshape(3,3) print(A+B) print(A*B) # 矩阵的积 print(np.dot(A,B)) print(A.dot(B)) print(np.dot(B,A)) ‘‘‘ ‘‘‘ a = np.arange(10,19).reshape(3,3) print(a) # 取单个值 print(a[1,2]) a = np.arange(1,17).reshape(4,4) print(a) # 切一行 print(a[1,:]) # 切一列 print(a[:,2]) # 抽取小矩阵 print(a[0:3,1:4]) # 抽取索引不连续 print(a[[0,3],0:2]) ‘‘‘ ‘‘‘ # 数组迭代 a = np.arange(11,27).reshape(4,4) print(a) # 遍历行 # for row in a: # print(row) # 遍历每一个元素 # for i in a.flat: # print(i) # 按列进行迭代(axis 控制行列) num = np.apply_along_axis(np.mean,axis=0,arr=a) print(num) # 按行进行迭代(计算每一行的平均数) num = np.apply_along_axis(np.mean,axis=1,arr=a) print(num) def foo(x): return x/2 num = np.apply_along_axis(foo,axis=0,arr=a) print(num) num = np.apply_along_axis(foo,axis=1,arr=a) print(num) ‘‘‘ ‘‘‘ A = np.random.random((4,4)) # 布尔数组 print(A<0.5) # 抽取小于0.5的元素 print(A[A<0.5]) a = np.random.random(12) print(a) A = a.reshape(3,4) print(A) a.shape = (3,4) print(a) # 变回原型 a = a.ravel() print(a) a.shape = (12) print(a) # 交换行列位置 print(A.transpose()) ‘‘‘ ‘‘‘ A = np.ones((3,3)) B = np.zeros((3,3)) # 垂直连接 print(np.vstack((A,B))) # 水平连接 print(np.hstack((A,B))) A = np.arange(0,16).reshape(4,4) B = np.array([1,2,3,4]) print(np.column_stack((A,B))) print(np.row_stack((A,B))) [B,C] = np.hsplit(A,2) print(B) print(C) [B,C] = np.vsplit(A,2) print(B) print(C) # 按列切分 [A1,A2,A3] = np.split(A,[1,3],axis=1) print(A1) print(A2) print(A3) ‘‘‘ ‘‘‘ a = np.array([1,2,3,4]) b = a a[2] = 0 print(b) c = a.copy() a[1] = 0 print(a) print(c) # 注意与Python列表区分,列表操作得到的是副本 a = np.array([1,2,3,4]) c = a[0:2] print(c) a[0] = 0 print(c) ‘‘‘ m = np.arange(6).reshape(3,1,2) n = np.arange(6).reshape(3,2,1) print(m) print(n) # 结构不同需扩展维度 print(m+n)