- 创建多维数组,维度相当于坐标轴的个数(the number of axes (dimensions) of the array.官方解释)
note:个人理解np.array()最多创建到3维数组,维度分别对应(x,y,z),不知正确与否,一般使用二维数组即可#4个4*4矩阵,整体维数还是3 a = np.array([ [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]],#x和y,后面的都理解为z [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]], [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]], [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]] ]) #a 3D array (four stacked 2D arrays),a.shape=(4,4,4)代表4个4*4矩阵 print(a) print(a.ndim)#输出还是3 #等价于 a = np.array([ [(1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4)], [(1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4)], [(1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4)], [(1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4)], ])
note:()和[]在数组中有时可以互换,比如:
a = np.zeros([3, 4]) #等同于 a = np.zeros((3,4))
-
利用ones()函数一次性初始化多个相同大小的矩阵,利用下标索引矩阵,比1创建多个矩阵简单很多
a = np.ones((4, 3, 4))
-
可以利用arange()创建x坐标序列,画图时可以用到,也可以用linespace()替代,更精确灵活
a = np.arange(0, 61, 1) # 0,1,2,...,61
-
矩阵索引从0开始,左闭右开:b[1:3,:]代表b的第二行(1),第三行(2)元素
-
def f(x, y): return x+y # shape(5,4)代表x,y均为行列式,x = [0,1,2,3,4]; y = [0,1,2,3] b = np.fromfunction(f, (5, 4), dtype=int)
对于np.fromfunction()函数,shape(x,y),x的每一个元素和y的所有元素通过函数运算,最后得出一个大矩阵
-
# Linear Algebra a = np.array([ [1, 2], [3, 4] ]) a.transpose() np.linalg.inv(a) # 求逆 a = np.eye(2) # 创建2*2单位矩阵 np.trace(a) # 求迹 # 求解线性方程组 y = np.array([[5], [7]]) np.linalg.solve(a, y) # Tricks And Tips # “Automatic” Reshaping a = np.arange(30) # 左闭右开[0,30) a.shape = 2, -1, 3 # -1 means "whatever is needed":2个x*3矩阵 # Vector Stacking x = np.arange(0,10,2) # x=([0,2,4,6,8]) y = np.arange(5) # y=([0,1,2,3,4]) m = np.vstack([x,y]) # m=([[0,2,4,6,8], # [0,1,2,3,4]]) xy = np.hstack([x,y]) # xy =([0,2,4,6,8,0,1,2,3,4])
-
绘制直方图
# Histograms import matplotlib.pyplot as plt plt.figure(num = 1) mu, sigma = 2, 0.5 v = np.random.normal(mu, sigma, 10000) plt.hist(v, bins = 50, density = 1) plt.show() plt.figure(num = 2) (n, bins) = np.histogram(v, bins = 50, density = True) print(bins) plt.plot(0.5*(bins[1:]+bins[:-1]), n) plt.show()
其中的bins为一维向量,代表直方图所有的边界,bin[1:]从第2个元素开始索引,bin[:-1]索引到倒数第二个元素,同一个向量的交叉运算,也是经常用到