将三维ndarray重塑为二维

问题描述 投票:1回答:2

我有一个三维数组(形状是2,2,3),它可以被认为是两个二维数组的组合。我想得到这两个阵列并将它们放在一起。这是我的出发点:

test1 = np.ndarray((2,2,3))
test1[0] = np.array([[1,2,3],
                     [4,5,6]])
test1[1] = np.array([[7,8,9],
                     [10,11,12]])

通过迭代第一个维度,我可以达到预期的结果,喜欢:

output = np.ndarray((2,6))
for n_port, port in enumerate(test1):
    output[:,n_port*3:(n_port+1)*3] = port  

这使:

array([[ 1.,  2.,  3.,  7.,  8.,  9.],
       [ 4.,  5.,  6., 10., 11., 12.]])

但我想知道是否有一种更流畅的方式来做到这一点。重塑功能将是显而易见的方法,但它会使它们变平,而不是并排堆叠它们:

test1.reshape((2,6))
array([[ 1.,  2.,  3.,  4.,  5.,  6.],
       [ 7.,  8.,  9., 10., 11., 12.]])

任何帮助感激不尽!

python arrays numpy multidimensional-array reshape
2个回答
1
投票

你可以先做一个swapaxes(),然后reshape()

test1.swapaxes(0,1).reshape(2,6)

2
投票

基于线程:intuition and idea behind reshaping 4D array to 2D array in numpy中描述的回溯思路,您可以使用arr.transposearr.reshape的组合,如:

In [162]: dd = np.arange(1, 13).reshape(2, 2, 3)

In [163]: dd
Out[163]: 
array([[[ 1,  2,  3],
        [ 4,  5,  6]],

       [[ 7,  8,  9],
        [10, 11, 12]]])

In [164]: dd.transpose((1, 0, 2))
Out[164]: 
array([[[ 1,  2,  3],
        [ 7,  8,  9]],

       [[ 4,  5,  6],
        [10, 11, 12]]])

In [165]: dd.transpose((1, 0, 2)).reshape(2, -1)
Out[165]: 
array([[ 1,  2,  3,  7,  8,  9],
       [ 4,  5,  6, 10, 11, 12]])
© www.soinside.com 2019 - 2024. All rights reserved.