Python 数据分析 之numpy的形状
—b站 python数据分析(黑马程序员)
1.查看数组的形状,shape
t1 = np.arange(12)
print(t1.shape)
t2 = np.array([[1, 2, 3, 4, 5],
[2, 3, 4, 5, 6]])
print(t2.shape)
(12,)
(2, 5)
Process finished with exit code 0
调用shape返回一个类型为元组的对象,元组的第一个值代表数组的行,第二个值代表数组的列
特别注意: 这里的一维数组形状为(12,)而不是(12,1)或(1,12)
2.修改数组的形状,reshape
reshape中放的参数为数据的类型,可以写reshape(3,4)也可以写reshape((3,4))
并且reshape函数有返回值,不改变原来的t1
t3 = t1.reshape((3, 4))
# t3 = t1.reshape(3, 4)
print(t3)
t4 = t1.reshape(2, 3, 2) #三维
# t4 = t1.reshape((2, 3, 2))
print(t4)
print(t1)
t3:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
t4:
[[[ 0 1]
[ 2 3]
[ 4 5]]
[[ 6 7]
[ 8 9]
[10 11]]]
t1:
[ 0 1 2 3 4 5 6 7 8 9 10 11]
Process finished with exit code 0
3.将多维数组修改为一维
flatten()函数的运用
t5 = t4.flatten()
print(t5) # [ 0 1 2 3 4 5 6 7 8 9 10 11]
t6 = t4.reshape(t4.shape[0] * t4.shape[1] * t4.shape[2], )
print(t6) # [ 0 1 2 3 4 5 6 7 8 9 10 11]