Numpy 从平坦数组重塑

huangapple go评论68阅读模式
英文:

Numpy reshaping from flattened

问题

以下是翻译好的部分:

从这个numpy数组中获取:

array([[[2, 1],
        [4, 3]],

       [[2, 0],
        [2, 3]]])

即:将跳过的元素放入两个矩阵中。

请告诉如何对任意数量的最终矩阵(在示例中为2)和它们的维度(始终相等;在示例中为2x2)进行操作。

我尝试了reshape(2,2,2,1)但结果是:

array([[[[2],
         [2]],

        [[1],
         [0]]],


       [[[4],
         [2]],

        [[3],
         [3]]]])
英文:

Some code results in the numpy array: array([[2, 2, 1, 0, 4, 2, 3, 3]])

From which, I want to recover:

array([ [[2, 1], 
         [4, 3]], 

         [[2, 0], 
          [2, 3]] ])

ie: place skipping elements into two matrices.

Please advise on how this can be achieved for arbitrary number of final matrices (2 in toy example) and their dimensions (always equal to one another; 2x2 in toy example).

I tried and failed with reshape(2,2,2,1) which results in:

array([[[[2],
         [2]],

        [[1],
         [0]]],


       [[[4],
         [2]],

        [[3],
         [3]]]])

答案1

得分: 1

Here is the translated code:

    In [195]: arr = np.array([[2, 2, 1, 0, 4, 2, 3, 3]])

    In [196]: arr.reshape(2,2,2)
    Out[196]: 
    array([[[2, 2],
            [1, 0]],

           [[4, 2],
            [3, 3]]])

first guess on transpose - 

    In [197]: arr.reshape(2,2,2).transpose(2,1,0)
    Out[197]: 
    array([[[2, 4],
            [1, 3]],

           [[2, 2],
            [0, 3]]])

not quite, switching the last 2 dimensions correct that:

    In [198]: arr.reshape(2,2,2).transpose(2,0,1)
    Out[198]: 
    array([[[2, 1],
            [4, 3]],

           [[2, 0],
            [2, 3]]])

This is the translated code without the request for translation or additional content.

英文:
In [195]: arr = np.array([[2, 2, 1, 0, 4, 2, 3, 3]])

In [196]: arr.reshape(2,2,2)
Out[196]: 
array([[[2, 2],
        [1, 0]],

       [[4, 2],
        [3, 3]]])

first guess on transpose -

In [197]: arr.reshape(2,2,2).transpose(2,1,0)
Out[197]: 
array([[[2, 4],
        [1, 3]],

       [[2, 2],
        [0, 3]]])

not quite, switching the last 2 dimensions correct that:

In [198]: arr.reshape(2,2,2).transpose(2,0,1)
Out[198]: 
array([[[2, 1],
        [4, 3]],

       [[2, 0],
        [2, 3]]])

huangapple
  • 本文由 发表于 2023年4月20日 08:07:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/76059646.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定