Ren*_*hya 2 python arrays numpy
我想创建一个3D NumPy数组,其序列号如下:
[[[11 27 43]
[12 28 44]
[13 29 45]
[14 30 46]]
[[15 31 47]
[16 32 48]
[17 33 49]
[18 34 50]]
[[19 35 51]
[20 36 52]
[21 37 53]
[22 38 54]]
[[23 39 55]
[24 40 56]
[25 41 57]
[26 42 58]]]
Run Code Online (Sandbox Code Playgroud)
我做到了这一点:A = np.arange(11, 59).reshape((4, 4, 3))但我得到了这个:
[[[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]]]
Run Code Online (Sandbox Code Playgroud)
所以这不是我想要的顺序.我已经做了一些额外的步骤来获得正确的3D阵列.首先,我将数字整形为2D数组:A = np.arange(11, 59).reshape((-1, 4))得到这个:
[[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]]
Run Code Online (Sandbox Code Playgroud)
然后,我拆分并堆叠了2D数组并获得了我想要的3D数组: A = np.dstack(np.vsplit(A, 3))
[[[11 27 43]
[12 28 44]
[13 29 45]
[14 30 46]]
[[15 31 47]
[16 32 48]
[17 33 49]
[18 34 50]]
[[19 35 51]
[20 36 52]
[21 37 53]
[22 38 54]]
[[23 39 55]
[24 40 56]
[25 41 57]
[26 42 58]]]
Run Code Online (Sandbox Code Playgroud)
现在我想知道是否有更优雅和直接的方式来实现相同的结果.谢谢.
获取远程数组,重新整形然后置换轴 -
np.arange(11, 59).reshape(3,4,4).transpose(1,2,0)
Run Code Online (Sandbox Code Playgroud)
置换轴的另一种方法是使用np.moveaxis-
np.moveaxis(np.arange(11, 59).reshape(3,4,4),0,2)
Run Code Online (Sandbox Code Playgroud)
Discussion : A general intuition to solving such problems.
| 归档时间: |
|
| 查看次数: |
74 次 |
| 最近记录: |