2 篇文章 0 订阅

# 把二维数组拆分为三维数组

import numpy as np
a = np.arange(30)
a.resize(6,5)
a
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, 24],
[25, 26, 27, 28, 29]])
a.reshape(3,2,5) # 3页，2行，5列
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, 24],
[25, 26, 27, 28, 29]]])


# 把三维数组拆为四维数组

a=np.arange(60)
a.resize(6,2,5)
a
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, 24],
[25, 26, 27, 28, 29]],
[[30, 31, 32, 33, 34],
[35, 36, 37, 38, 39]],
[[40, 41, 42, 43, 44],
[45, 46, 47, 48, 49]],
[[50, 51, 52, 53, 54],
[55, 56, 57, 58, 59]]])
a.resize(3, 2, 2, 5)
a
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, 24],
[25, 26, 27, 28, 29]],
[[30, 31, 32, 33, 34],
[35, 36, 37, 38, 39]]],
[[[40, 41, 42, 43, 44],
[45, 46, 47, 48, 49]],
[[50, 51, 52, 53, 54],
[55, 56, 57, 58, 59]]]])


a从6页2行5列，被拆为3部分2页2行5列，可以看到直接用resize把待拆分数组的第一维直接因子分解，得到的拆分结果不会乱序。

a.transpose(0, 2, 1, 3)
array([[[[ 0,  1,  2,  3,  4],
[10, 11, 12, 13, 14]],
[[ 5,  6,  7,  8,  9],
[15, 16, 17, 18, 19]]],
[[[20, 21, 22, 23, 24],
[30, 31, 32, 33, 34]],
[[25, 26, 27, 28, 29],
[35, 36, 37, 38, 39]]],
[[[40, 41, 42, 43, 44],
[50, 51, 52, 53, 54]],
[[45, 46, 47, 48, 49],
[55, 56, 57, 58, 59]]]])


b=numpy.array([[1,2],[3,4]])
c=b.transpose(1,0)
b
Out[16]:
array([[1, 2],
[3, 4]])
c
Out[17]:
array([[1, 3],
[2, 4]])

• 6
点赞
• 0
评论
• 17
收藏
• 一键三连
• 扫一扫，分享海报

01-12 1万+

09-18
07-20 312
10-09 2万+
10-15 7万+
05-22 5万+
01-11 2万+
05-29 1万+
08-01 2万+
03-01 1万+
02-24 8364