Numpy优化重塑:从2D阵列到3D

时间:2019-02-16 16:12:12

标签: python python-3.x numpy reshape numpy-ndarray

我想知道是否有更pythonic /更有效的方法将我的2d数组重塑为3d数组?这是以下工作代码:

def mousePressEvent(self, event):
    w = 16.0
    x = int(event.x()*1.0/w)
    y = int(event.y()*1.0/w)
    s1, s2 = self.grid.shape
    # verify
    if 0 <= y < s1 and 0 <= x < s2:
        self.grid[x][y] = -self.grid[x][y]
        self.viewport().update()  

这是原始预期输出:

import numpy as np
#
# Declaring the dimensions
n_ddl = 2
N = 3
n_H = n_ddl*N
#
# Typical 2D array to reshape
x_tilde_2d = np.array([[111,112,121,122,131,132],[211,212,221,222,231,232],[311,312,321,322,331,332]])
x_tilde_2d = x_tilde_2d.T
#
# Initialization of the output 3D array
x_tilde_reshaped_3d = np.zeros((N,x_tilde_2d.shape[1],n_ddl))
for i in range(0,x_tilde_2d.shape[1],1):
    x_tilde_sol = x_tilde_2d[:,i]
    x_tilde_sol_reshape = x_tilde_sol.reshape((N,n_ddl))
    for j in range(0,n_ddl,1):
        x_tilde_reshaped_3d[:,i,j] = x_tilde_sol_reshape[:,j]

和相同的输出,沿轴= 2:

array([[[111., 112.],
        [211., 212.],
        [311., 312.]],

       [[121., 122.],
        [221., 222.],
        [321., 322.]],

       [[131., 132.],
        [231., 232.],
        [331., 332.]]])

任何建议将不胜感激。谢谢。

2 个答案:

答案 0 :(得分:2)

为什么不直接做一个reshape。似乎不需要首先初始化一个零的3d矩阵,然后按维度对其进行填充。

可以使用swapaxes(0, 1)

交换第一轴和第二轴来获得所需的顺序

修改后的答案

x_tilde_2d = np.array([[111,112,121,122,131,132],[211,212,221,222,231,232],[311,312,321,322,331,332]])
x_tilde_reshaped_3d  = x_tilde_2d.reshape(N, x_tilde_2d.T.shape[1], n_ddl).swapaxes(0, 1)
print (x_tilde_reshaped_3d)

输出

[[[111 112]
  [211 212]
  [311 312]]

 [[121 122]
  [221 222]
  [321 322]]

 [[131 132]
  [231 232]
  [331 332]]]

答案 1 :(得分:2)

In [337]: x=np.array([[111,112,121,122,131,132],[211,212,221,222,231,232],[311,3
     ...: 12,321,322,331,332]])
In [338]: x.shape
Out[338]: (3, 6)
In [339]: x
Out[339]: 
array([[111, 112, 121, 122, 131, 132],
       [211, 212, 221, 222, 231, 232],
       [311, 312, 321, 322, 331, 332]])

使最后一个尺寸保持正确顺序的唯一重塑是:

In [340]: x.reshape(3,3,2)
Out[340]: 
array([[[111, 112],
        [121, 122],
        [131, 132]],

       [[211, 212],
        [221, 222],
        [231, 232]],

       [[311, 312],
        [321, 322],
        [331, 332]]])

现在只需交换前两个维度:

In [341]: x.reshape(3,3,2).transpose(1,0,2)
Out[341]: 
array([[[111, 112],
        [211, 212],
        [311, 312]],

       [[121, 122],
        [221, 222],
        [321, 322]],

       [[131, 132],
        [231, 232],
        [331, 332]]])