【问题标题】:Numpy specific reshape order for 2D Array二维数组的 Numpy 特定重塑顺序
【发布时间】:2019-05-13 18:41:00
【问题描述】:

我有一个 4x3 矩阵,我需要将其重塑为具有特定顺序的 2x6 矩阵:

初始: |1 5 9| |2 6 10| |3 7 11| |4 8 12|

想要: |1 2 5 6 9 10| |3 4 7 8 11 12|

我尝试使用 numpy,但顺序不是我所期望的:

import numpy as np
a=np.array([[1,5,9],[2,6,10],[3,17,11],[4,8,12]])
b=a.reshape(2,6)
print(a)
print(b)

【问题讨论】:

标签: python-3.x numpy reshape


【解决方案1】:

Reshape, permute and reshape-

In [51]: n = 2 # no. of rows to select from input to form each row of output

In [52]: a.reshape(-1,n,a.shape[1]).swapaxes(1,2).reshape(-1,n*a.shape[1])
Out[52]: 
array([[ 1,  2,  5,  6,  9, 10],
       [ 3,  4, 17,  8, 11, 12]])

一种解释:

  1. 沿第一个轴剪切以得到3D 数组,这样我们就可以沿第二个轴选择n。将第二个轴与最后一个(第三个)轴交换,以便我们将第二个轴推回到最后。

  2. 重塑为 2D 以合并最后两个轴。这就是我们的输出!

有关更深入的信息,请参阅链接的问答。


如果给定输出中的行数 -

In [54]: nrows = 2 # number of rows in output

In [55]: a.reshape(nrows,-1,a.shape[1]).swapaxes(1,2).reshape(nrows,-1)
Out[55]: 
array([[ 1,  2,  5,  6,  9, 10],
       [ 3,  4, 17,  8, 11, 12]])

【讨论】:

  • 你能避免swapaxes 和order='F' 进行最终重塑吗? a.reshape(-1,n,a.shape[1]).reshape(-1,n*a.shape[1], order='F')
  • @user3483203 不,我们不能。 ravel('F') 改变了整个顺序。
  • 太棒了!您能解释一下吗,因为我想将您的解决方案转换为 8x3 => 2x12 矩阵。 [[ 1 9 17] [ 2 10 18] [ 3 11 19] [ 4 12 20] [ 5 13 21] [ 6 14 22] [ 7 15 23] [ 8 16 24]] => [[ 1 9 17 2 10 18 3 11 19 4 12 20] [ 5 13 21 6 14 22 7 15 23 8 16 24]]
  • @Divakar,很抱歉错过了你的链接!
  • @Divakar,明白了: import numpy as np a=np.array([[1,9,17],[2,10,18],[3,11,19],[ 4,12,20],[5,13,​​21],[6,14,22],[7,15,23],[8,16,24]]) b=a.reshape(-1,4 ,a.shape[1]).swapaxes(1,2).reshape(-1,4*a.shape[1]) print(a) print(b)
猜你喜欢
  • 1970-01-01
  • 2021-03-15
  • 1970-01-01
  • 1970-01-01
  • 2020-02-20
  • 2014-04-21
  • 2021-09-25
  • 1970-01-01
  • 2019-12-05
相关资源
最近更新 更多