Numpy
一. Numpy 常用操作
a. xxxx
import numpy as np print(np.arange(1,11)) #[ 1 2 3 4 5 6 7 8 9 10] print(np.arange(1,11).reshape([2,5])) # [ # [ 1 2 3 4 5] # [ 6 7 8 9 10] # ] li = np.arange(1,11).reshape([2,5]) print(li) # [ # [ 1 2 3 4 5] # [ 6 7 8 9 10] # ] print(np.exp(li)) #自然指数 # [ # [ 2.71828183e+00 7.38905610e+00 2.00855369e+01 5.45981500e+01 1.48413159e+02] # [ 4.03428793e+02 1.09663316e+03 2.98095799e+03 8.10308393e+03 2.20264658e+04] # ] print(np.exp2(li)) #自然指数的平方 # [ # [ 2. 4. 8. 16. 32.] # [ 64. 128. 256. 512. 1024.] # ] print(np.sqrt(li)) #开方 # [ # [ 1. 1.41421356 1.73205081 2. 2.23606798] # [ 2.44948974 2.64575131 2.82842712 3. 3.16227766] # ]
b. 单个数组操作
li = np.array([ [[1,2,3,4],[4,5,6,7]], [[7,8,9,10],[10,11,12,13]], [[14,15,16,17],[18,19,20,21]] ]) print(li.sum()) #求和 #252 print(li.sum(axis=0)) #最外层 # [ # [22 25 28 31] # [32 35 38 41] # ] print(li.sum(axis=1)) #第一层 # [ # [ 5 7 9 11] # [17 19 21 23] # [32 34 36 38] # ] print(li.sum(axis=2)) # [ # [10 22] # [34 46] # [62 78] # ]
c. 多个数组操作
#多个数组操作 li1 = np.array([10,20,30,40]) li2 = np.array([4,3,2,1]) print(li1.reshape([2,2]),li2.reshape([2,2])) # [ [10 20][30 40] ] # [ [4 3][2 1] ] print(np.dot(li1.reshape([2,2]),li2.reshape([2,2]))) # [ [ 80 50][200 130] ] print(np.concatenate((li1,li2))) #追加 # [10 20 30 40 4 3 2 1] print(np.vstack((li1,li2))) # [[10 20 30 40] [ 4 3 2 1]] print(np.hstack((li1,li2))) # [10 20 30 40 4 3 2 1] print(np.split(li1,2)) #分开 #[array([10, 20]), array([30, 40])]
二. 线性方程组 矩阵
import numpy as np from numpy.linalg import * #numpy 线性方程组 和矩阵 #print(np.eye(3)) #矩阵 #[[ 1. 0. 0.] # [ 0. 1. 0.] # [ 0. 0. 1.]] li = np.array([ #自定义矩阵 [1.,2.],[3.,4.] ]) #print(li) # [[ 1. 2.][ 3. 4.]] print(inv(li)) # [[-2. 1. ][ 1.5 -0.5]] print(li.transpose()) # [[ 1. 3.][ 2. 4.]] print(det(li)) # -2.0 print(eig(li)) #(array([-0.37228132, 5.37228132]), array([[-0.82456484, -0.41597356],[ 0.56576746, -0.90937671]]))