import numpy as np
A=np.arange(14,2,-1).reshape((3,4))print(A)'''索引'''#最小值的索引print(np.argmin(A))#索引的值print(A[1][2])print(A[1,2])#所有行第一列的值print(A[:,1])'''矩阵计算'''#矩阵的平均值print(np.mean(A))print(A.mean())print(np.average(A))#矩阵的中位数print(np.median(A))#矩阵累加print(np.cumsum(A))#矩阵排序print(np.sort(A))#矩阵转置print(A.T)#对矩阵元素进行比较print(np.clip(A,5,9))#迭代器print(A.flatten())#逐项输出for item in A.flat:print(item,end='\t')
矩阵合并
import numpy as np
A=np.array([1,1,1])
B=np.array([2,2,2])'''矩阵合并'''#上下合并
C=np.vstack((A,B))print(C)#左右合并
D=np.hstack((A,B))print(D)'''矩阵维度变换'''#对数组加维度print(A.shape)print(A[:,np.newaxis].shape)#对列数加维度print(A[:,np.newaxis])print(A[np.newaxis,:].shape)#对行数加维度print(A[np.newaxis,:])#数组合并print(np.concatenate((A,B,B,A),axis=0))#行合并
F=np.array([1,1,1])[:,np.newaxis]
G=np.array([2,2,2])[:,np.newaxis]print(np.concatenate((G,F,F,G),axis=1))#列合并
矩阵分割
import numpy as np
A=np.arange(12).reshape(3,4)print(A)'''等项分割'''#纵向分割为两个数组print(np.hsplit(A,2))print(np.split(A,2,axis=1))#横向分割为三个数组print(np.vsplit(A,3))print(np.split(A,3,axis=0))'''不等项分割'''#不等量分割print(np.array_split(A,3,axis=1))
矩阵元素赋值
import numpy as np
A=np.arange(4)#A与B同步变化
B=A
print(A)
A[1]=12print(A)print(B is A)print(B)#深度赋值
A=np.arange(4)#A与C不同步变化
C=A.copy()
A[1]=12
numpy基础运算矩阵的生成import numpy as npa=np.array([[1,2,3],[4,5,6]])print(a)#0矩阵b=np.zeros((3,4))print(b)#1矩阵c=np.ones((3,3))print(c)#3行4列矩阵d=np.arange(12).reshape(3,4)print(d)#在指定的间隔内返回均匀间隔的数字e=np.linspace(1,10,5)print(e)#随机产生矩阵a=np.random.rand