import numpy as np
# t1 一维数组
t1 = np.arange(12)
print(t1,t1.shape)
# 查看数组的形状
print(t1.shape)
# t1 二维数组
t2 = np.array([[1,2,3],[4,5,6]])
print(t2,t2.shape)
# t3 三维数组
t3 = np.array([[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]]])
print(t3,t3.shape)
# 结果
[ 0 1 2 3 4 5 6 7 8 9 10 11] (12,)
(12,)
[[1 2 3]
[4 5 6]] (2, 3)
[[[ 1 2 3]
[ 4 5 6]]
[[ 7 8 9]
[10 11 12]]] (2, 2, 3)
t4 = np.arange(12)
...: print(t4,t4.shape)
[ 0 1 2 3 4 5 6 7 8 9 10 11] (12,)
t4.reshape((3,4))
Out[4]:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
t5 = np.arange(24).reshape((2,3,4))
...: print(t5)
[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[12 13 14 15]
[16 17 18 19]
[20 21 22 23]]]
# 一维数组转化为三维数组
t5 = np.arange(24).reshape((2,3,4))
print(t5)
[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[12 13 14 15]
[16 17 18 19]
[20 21 22 23]]]
# t5 三维数组转化为一维数组
t5.reshape((24,))
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23])
# t5 三维数组转化为二维数组
t5.reshape((24,1))
array([[ 0],
[ 1],
[ 2],
[ 3],
[ 4],
[ 5],
[ 6],
[ 7],
[ 8],
[ 9],
[10],
[11],
[12],
[13],
[14],
[15],
[16],
[17],
[18],
[19],
[20],
[21],
[22],
[23]])
# t5 三维数组转化为二维数组
t5.reshape((1,24))
array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23]])
# 当数组t5的维数未知时,可采用shape属性的数组结果下标来计算t5的元素个数转化为一维数组
t6 = t5.reshape((t5.shape[0]*t5.shape[1]*t5.shape[2],))
print(t6)
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]
# 当数组t5的维数未知时,可采用flatten()转化为一维数组
t5.flatten()
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23])