1、shape
在python中导入numpy库之后,我们可以通过矩阵的属性shape获取矩阵的维度。
如图所示:
import numpy as np
b= np.array([[1,2,3,4],[5,6,7,8]])
print(b)
print(b.shape) #输出行数和列数
print(b.shape[0]) #输出行数
print(b.shape[1]) #输出列数
print(b.shape[2]) # 错误,超出元组维度
##
##打印结果:
## [[1 2 3 4]
## [5 6 7 8]]
## (2, 4)
## 2
## 4
##
2、reshape
用于改变数组的形状,如图所示:
b= np.array([[1,2,3,4],[5,6,7,8]])
c=b.reshape(4,2)
print(b)
print(c)
##[[1 2 3 4]
##[[5 6 7 8]]
##[[1 2]
##[3 4]
##[5 6]
##[7 8]]
这里要注意,reshape新生成数组和原数组公用一个内存,改变某一个元素,对所有结果会有影响。
这里就不贴出来了。