1 import numpy as np 2 # 基础属性 3 array = np.array([[[1,2,3], [0,0,1]], [[1,2,3], [0,0,1]]], 4 dtype = np.int64) 5 6 print(array) 7 print(array.ndim) # number of dim 8 print(array.shape) # shape 9 print(array.size) # number of elements 10 print(array.dtype) 11 12 # 创建array 13 a = np.array([1,2,3,4]) # 1 dim 14 15 b = np.array([[1,2,3,4]]) # row vector, 2 dim 16 c = np.array([[1], [2], [3] ,[4]]) # column vector, 2 dim 17 print(a.shape, b.shape, c.shape) 18 19 a = np.zeros( (2,3), dtype = np.float) 20 a = np.ones( (2,3), dtype = np.float) 21 a = np.empty( (2,3), dtype = np.float) 22 a = np.arange(10, 20) # alike function range 23 a = np.linspace(1, 10, 5) # interval 24 print(a) 25 26 # 基础运算(向量式运算) 27 '''向量''' 28 a = np.array([10, 20, 30, 40]) 29 b = np.arange(4) 30 print( a + b) 31 print( a**2) 32 print( a < 20) 33 34 '''矩阵''' 35 a = np.array([[1,1], 36 [0,1]]) 37 b = np.arange(4).reshape((2,2)) 38 print( a*b ) 39 print( np.dot(a, b) ) # equal a.dot(b) 40 41 print(np.argmax(a)) 42 print(np.argmin(a)) 43 44 A = np.arange(14, 2, -1).reshape((3,4)) 45 print(np.clip(A, 5, 9)) 46 47 '''随机数''' # module: np.random 48 a = np.random.random((2,4)) 49 print(a) 50 print(np.sum(a, axis = 1)) 51 print(np.min(a, axis = 0)) 52 53 # 索引 54 '''一维array''' 55 A = np.arange(3, 15) 56 print(A[2]) 57 print(A[0:5:2]) 58 59 '''二维array''' 60 A = np.arange(3, 15).reshape(3, 4) 61 print(A[2]) 62 print(A[2,:]) 63 64 print(A[2][1]) 65 print(A[2, 1]) 66 67 # array合并 68 A = np.array([1,1,1]) 69 B = np.array([2,2,2]) 70 71 print(np.vstack((A,B))) # vertival stack 72 print(np.hstack((A,B))) # horizontal stack 73 74 A[np.newaxis, :] # 1 * 3 75 A[:, np.newaxis] # 3 * 1 76 77 a = np.array([[1, 2], [3, 4]]) 78 b = np.array([[5, 6]]) 79 80 # array分割 81 A = np.arange(12).reshape((3,4)) 82 83 print(np.split(A, 2, axis = 1)) 84 print(np.array_split(A, 3, axis = 1)) 85 print(np.split(A, 3, axis = 0)) 86 87 print(np.vsplit(A, 3)) 88 print(np.hsplit(A, 2)) 89 90 # copy and deep copy 91 a = np.array([1,2,3,10]) 92 b = a 93 c = a 94 d = b 95 96 b = a.copy() 97 a[3] = 44 98 print(a) 99 print(b)