这是Numpy的第二篇,第一篇可以看此链接
【Numpy第一讲】如何生成矩阵,如何对矩阵进行加减乘除
更改矩阵的维度
使用np.reshape()函数
使用方法:
import numpy as np
矩阵 = np.array([1,2,3,4,5,6,7,8])
# 将它重新形状为2行4列的二维数组
reshape后 = np.reshape(矩阵,(2, 4))
print(reshape后)
r e s h a p e 后 = [ 1 2 3 4 5 6 7 8 ] reshape后=\begin{bmatrix} 1 & 2 & 3 & 4\\ 5&6&7&8 \\ \end{bmatrix} reshape后=[15263748]
用户可以自行设置修改后的行列数值,此时我们将一个一位的数组转换为了二行四列的数组,函数将会自动将他们转换为对应的形状。
但如果无法满足新数组的大小,那么就会报错。
此外,无需将行列两个数都给出,倘若只给出一个,将另外一个填为-1,函数会自动计算另一个参数
import numpy as np
矩阵 = np.array([1,2,3,4,5,6,7,8])
# 将它重新形状为4列的二维数组
reshape后 = np.reshape(矩阵,(4, -1))
print(reshape后)
r e s h a p e 后 = [ 1 2 3 4 5 6 7 8 ] reshape后=\begin{bmatrix} 1 & 2 \\ 3 & 4\\ 5&6 \\ 7&8 \\ \end{bmatrix} reshape后=