重塑多个numpy数组

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

我有以下numpy数组:

X = [[1],
     [2],
     [3],
     [4]]

Y = [[5],
     [6],
     [7],
     [8]]

Z = [[9],
     [10],
     [11],
     [12]]

我想得到以下输出:

H = [[1,5,9],
     [2,6,10],
     [3,7,11]
     [4,8,12]]

有没有办法使用numpy.reshape获得此结果?

python arrays numpy reshape numpy-ndarray
3个回答
3
投票

你可以使用np.column_stack -

np.column_stack((X,Y,Z))

np.concatenate沿axis=1 -

np.concatenate((X,Y,Z),axis=1)

或者np.hstack -

np.hstack((X,Y,Z))

np.stack沿着axis=0,然后进行多暗调换 -

np.stack((X,Y,Z),axis=0).T

Reshape适用于数组,而不是堆叠或连接数组。所以,单独的reshape在这里没有意义。

人们可以争论使用np.reshape给我们所需的输出,就像这样 -

np.reshape((X,Y,Z),(3,4)).T

但是,在引擎盖下进行堆叠操作,AFAIK是用np.asarray转换为阵列的东西 -

In [453]: np.asarray((X,Y,Z))
Out[453]: 
array([[[ 1],
        [ 2],
        [ 3],
        [ 4]],

       [[ 5],
        [ 6],
        [ 7],
        [ 8]],

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

我们只需要在它上面使用multi-dim transpose,给我们一个预期输出的3D数组版本 -

In [454]: np.asarray((X,Y,Z)).T
Out[454]: 
array([[[ 1,  5,  9],
        [ 2,  6, 10],
        [ 3,  7, 11],
        [ 4,  8, 12]]])

1
投票

这个(更快)的解决方案怎么样?

In [16]: np.array([x.squeeze(), y.squeeze(), z.squeeze()]).T
Out[16]: 
array([[ 1,  5,  9],
       [ 2,  6, 10],
       [ 3,  7, 11],
       [ 4,  8, 12]])

效率(降序)

# proposed (faster) solution
In [17]: %timeit np.array([x.squeeze(), y.squeeze(), z.squeeze()]).T
The slowest run took 7.40 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 7.36 µs per loop

# Other solutions
In [18]: %timeit np.column_stack((x, y, z))
The slowest run took 5.18 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 9.18 µs per loop

In [19]: %timeit np.hstack((x, y, z))
The slowest run took 4.49 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 16 µs per loop

In [20]: %timeit np.reshape((x,y,z),(3,4)).T
10000 loops, best of 3: 21.6 µs per loop

In [20]: %timeit np.c_[x, y, z]
10000 loops, best of 3: 55.9 µs per loop

0
投票

并且不要忘记np.c_(我不认为需要np.reshape):

np.c_[X,Y,Z]
# array([[ 1,  5,  9],
#        [ 2,  6, 10],
#        [ 3,  7, 11],
#        [ 4,  8, 12]])
© www.soinside.com 2019 - 2024. All rights reserved.