如何水平堆叠数组?

问题描述 投票:0回答:3

我有一个数组:

> a
array([[[1, 2, 3, 4],
        [5, 6, 7, 8],
        [9, 10, 11, 12],
        [13, 14, 15, 16]],
       [[17, 18, 19, 20], 
        [21, 22, 23, 24], 
        [25, 26, 27, 28], 
        [29, 30, 31, 32]]])

我怎样才能将其重塑为这样:

[[1, 2, 3, 4, 17, 18, 19, 20],
 [5, 6, 7, 8, 21, 22, 23, 24],
 [9, 10, 11, 12, 25, 26, 27, 28],
 [13, 14, 15, 16, 29, 30, 31, 32]]

我尝试过

reshape
函数,但它返回这个:

[[1, 2, 3, 4, 5, 6, 7, 8],
 [9, 10, 11, 12, 13, 14, 15, 16],
 [17, 18, 19, 20, 21, 22, 23, 24],
 [25, 26, 27, 28, 29, 30, 31, 32]]

有什么解决办法吗?

非常感谢

python arrays numpy multidimensional-array sub-array
3个回答
1
投票

您可以使用

moveaxis
将第一个轴推到底,然后按 Fortran 顺序使用
reshape

np.moveaxis(a, 0, -1).reshape((a.shape[1], -1), order='F')

输出:

array([[ 1,  2,  3,  4, 17, 18, 19, 20],
       [ 5,  6,  7,  8, 21, 22, 23, 24],
       [ 9, 10, 11, 12, 25, 26, 27, 28],
       [13, 14, 15, 16, 29, 30, 31, 32]])

1
投票

Numpy 通过 hstack 方法内置了此功能

a = np.array([[[1, 2, 3, 4],
        [5, 6, 7, 8],
        [9, 10, 11, 12],
        [13, 14, 15, 16]],
       [[17, 18, 19, 20], 
        [21, 22, 23, 24], 
        [25, 26, 27, 28], 
        [29, 30, 31, 32]]])

np.hstack(a)

# array([[ 1,  2,  3,  4, 17, 18, 19, 20],
#        [ 5,  6,  7,  8, 21, 22, 23, 24],
#        [ 9, 10, 11, 12, 25, 26, 27, 28],
#        [13, 14, 15, 16, 29, 30, 31, 32]])

0
投票

您可以使用

np.c_

np.c_[a[0], a[1]]

# [[ 1  2  3  4 17 18 19 20]
#  [ 5  6  7  8 21 22 23 24]
#  [ 9 10 11 12 25 26 27 28]
#  [13 14 15 16 29 30 31 32]]
© www.soinside.com 2019 - 2024. All rights reserved.