修改数组的维度

 1 #导入numpy模块
 2 import numpy as np 
 3 #通过reshape将一维数组修改为二、三维
 4 #创建一个一维数组
 5 a = np.arange(1,25)
 6 print(a)
 7 #将一维修改为二维(2,12) (4,6) (3,8)
 8 b = a.reshape((4,6))
 9 print(b)
10 #将一维数组修改为三维(2,3,4)
11 c = a.reshape((2,3,4))
12 print(c)
13 
14 #通过np.reshape()进行修改
15 bb = np.reshape(a,(3,8)) #将一维修改为二维
16 print(bb)
17 #将一维修改为三维
18 cc = np.reshape(a,(4,3,2))
19 print(cc)
20 
21 #将多维数组修改为一维数组
22 d = cc.reshape(24)
23 print(d)
24 dd = bb.reshape(-1)
25 print(dd)
26 
27 #通过ravel、flatten函数将多维数组转换维一维数组
28 #flatten
29 e = bb.flatten()
30 print(e)
31 #ravel
32 f = bb.ravel()
33 print(f)
 1 [ 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24]
 2 [[ 1  2  3  4  5  6]
 3  [ 7  8  9 10 11 12]
 4  [13 14 15 16 17 18]
 5  [19 20 21 22 23 24]]
 6 [[[ 1  2  3  4]
 7   [ 5  6  7  8]
 8   [ 9 10 11 12]]
 9 
10  [[13 14 15 16]
11   [17 18 19 20]
12   [21 22 23 24]]]
13 [[ 1  2  3  4  5  6  7  8]
14  [ 9 10 11 12 13 14 15 16]
15  [17 18 19 20 21 22 23 24]]
16 [[[ 1  2]
17   [ 3  4]
18   [ 5  6]]
19 
20  [[ 7  8]
21   [ 9 10]
22   [11 12]]
23 
24  [[13 14]
25   [15 16]
26   [17 18]]
27 
28  [[19 20]
29   [21 22]
30   [23 24]]]
31 [ 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24]
32 [ 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24]
33 [ 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24]
34 [ 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24]

猜你喜欢

转载自www.cnblogs.com/monsterhy123/p/12622915.html