Python把二维数组拆分为三维数组,把三维数组拆为四维数组

编程 专栏收录该内容
2 篇文章 0 订阅

说实话,我也奇怪我怎么会有这么奇怪的需求,,,

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

目标:把一个 m ∗ n m*n mn的数组,每x行为一页(x可被m整除),拆分为一个m行n列x页的三维数组

代码

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]]]])

注意a.transpose(0, 2, 1, 3)并不会概念a,如果要把转置得到的矩阵存下来就必须赋值,如b=a.transpose(0, 2, 1, 3),这样b就是转置后的矩阵,a并未变化。

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
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值