简体   繁体   English

通过 numpy.reshape() 交换 3D numpy 数组的列和行

[英]Swapping the columns and rows of a 3D numpy array by numpy.reshape()

Now I have a 3D numpy array with shape (2,3,4) as follows:现在我有一个形状为 (2,3,4) 的 3D numpy 数组,如下所示:

[[[ 0  1  2  3]
  [ 4  5  6  7]
  [ 8  9 10 11]]

 [[12 13 14 15]
  [16 17 18 19]
  [20 21 22 23]]]

Now, I want to reshape the array to (2,4,3) by swapping the last 2 dimensions of the array as follows:现在,我想通过交换数组的最后 2 个维度来将数组重塑为 (2,4,3),如下所示:

[[[ 0  4  8]
  [ 1  5  9]
  [ 2  6 10]
  [ 3  7 11]]

 [[12 16 20]
  [13 17 21]
  [14 18 22]
  [15 19 23]]]

In the documentation of numpy.reshape, there are 2 types of orders for reshaping numpy arrays, including 'C' and 'F'.在 numpy.reshape 的文档中,reshape numpy arrays 有两种类型的命令,包括'C'和'F'。 I tried to use them and the results are as follows:我尝试使用它们,结果如下:

  1. For order='C':对于订单='C':
    [[[ 0  1  2]
      [ 3  4  5]
      [ 6  7  8]
      [ 9 10 11]]
    
     [[12 13 14]
      [15 16 17]
      [18 19 20]
      [21 22 23]]]
  1. For order='F':对于订单='F':
 [[[ 0  5 10]
  [ 4  9  3]
  [ 8  2  7]
  [ 1  6 11]]

 [[12 17 22]
  [16 21 15]
  [20 14 19]
  [13 18 23]]]

I have also tried to do the reshaping consecutively, but still couldn't get my desired shape.我也尝试过连续进行整形,但仍然无法达到我想要的形状。 Do anyone know how to reshape the array in the desired order?有谁知道如何按所需顺序重塑数组?

It can be done with a transpose on the last two axes:它可以通过最后两个轴上的转置来完成:

arr = np.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]]])

np.transpose(arr, axes = (0,2,1))
array([[[ 0,  4,  8],
        [ 1,  5,  9],
        [ 2,  6, 10],
        [ 3,  7, 11]],

       [[12, 16, 20],
        [13, 17, 21],
        [14, 18, 22],
        [15, 19, 23]]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM