本文介绍了在Python中使用重整形来重整数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的数组:

I have an array that looks like below:

array([[0, 0, 0, 0, 0, 0, 0, 0],
       [1, 1, 1, 1, 1, 1, 1, 1],
       [2, 2, 2, 2, 2, 2, 2, 2],
       [3, 3, 3, 3, 3, 3, 3, 3],
       [4, 4, 4, 4, 4, 4, 4, 4],
       [5, 5, 5, 5, 5, 5, 5, 5],
       [6, 6, 6, 6, 6, 6, 6, 6],
       [7, 7, 7, 7, 7, 7, 7, 7]])

如何使用重塑将其分成4个卡盘,使其看起来像

How can I use reshape to divide it into 4 chucks, such that it looks like

array([[[0, 0, 0, 0],
       [1, 1, 1, 1],
       [2, 2, 2, 2],
       [3, 3, 3, 3]],
       [[0, 0, 0, 0],
       [1, 1, 1, 1],
       [2, 2, 2, 2],
       [3, 3, 3, 3]],
       [[4, 4, 4, 4],
       [5, 5, 5, 5],
       [6, 6, 6, 6],
       [7, 7, 7, 7]],
       [[4, 4, 4, 4],
       [5, 5, 5, 5],
       [6, 6, 6, 6],
       [7, 7, 7, 7]]])

我在reshape(m,n,l)中尝试了m,n,l的不同整数组合,但都无效.

I tried different integer combinations of m, n, l in reshape(m,n,l), but none works.

推荐答案

对不起,我没有意识到这是3维结果,而不是4维结果.要获得3-d,必须再次重塑形状.额外的整形 将复制数据.

Sorry, I didn't realize it was a 3-d result, not a 4-d result. To get the 3-d one, you would have to reshape once more. And that extra reshape will copy the data.

您不能,也需要转置:

In [1]: a = np.arange(8)[:,None].repeat(8,axis=1)

In [2]: a
Out[2]:
array([[0, 0, 0, 0, 0, 0, 0, 0],
       [1, 1, 1, 1, 1, 1, 1, 1],
       [2, 2, 2, 2, 2, 2, 2, 2],
       [3, 3, 3, 3, 3, 3, 3, 3],
       [4, 4, 4, 4, 4, 4, 4, 4],
       [5, 5, 5, 5, 5, 5, 5, 5],
       [6, 6, 6, 6, 6, 6, 6, 6],
       [7, 7, 7, 7, 7, 7, 7, 7]])

In [3]: b = a.reshape(2,4,2,4)

In [4]: b
Out[4]:
array([[[[0, 0, 0, 0],
         [0, 0, 0, 0]],
         ...
        [[7, 7, 7, 7],
         [7, 7, 7, 7]]]])

In [5]: b.transpose(0,2,1,3)
Out[5]:
array([[[[0, 0, 0, 0],
         [1, 1, 1, 1],
         [2, 2, 2, 2],
         [3, 3, 3, 3]],

        [[0, 0, 0, 0],
         [1, 1, 1, 1],
         [2, 2, 2, 2],
         [3, 3, 3, 3]]],


       [[[4, 4, 4, 4],
         [5, 5, 5, 5],
         [6, 6, 6, 6],
         [7, 7, 7, 7]],

        [[4, 4, 4, 4],
         [5, 5, 5, 5],
         [6, 6, 6, 6],
         [7, 7, 7, 7]]]])

这篇关于在Python中使用重整形来重整数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 10:48