NumPy堆栈或将数组附加到数组

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

我是从NumPy开始的。

鉴于两个np.arrays,queunew_path

queu = [ [[0 0]
          [0 1]]
       ]

new_path = [ [[0 0]
              [1 0]
              [2 0]]
           ]

我的目标是获得以下queu

queu = [ [[0 0]
          [0 1]]
         [[0 0]
          [1 0]
          [2 0]]
       ]

我试过了:

np.append(queu, new_path, 0)

np.vstack((queu, new_path))

但两者都在提高

除连接轴之外的所有输入数组维度必须完全匹配

我没有得到NumPy的理念。我究竟做错了什么?

python arrays numpy numpy-ndarray valueerror
3个回答
1
投票
In [741]: queu = np.array([[[0,0],[0,1]]])
In [742]: new_path = np.array([[[0,0],[1,0],[2,0]]])
In [743]: queu
Out[743]: 
array([[[0, 0],
        [0, 1]]])
In [744]: queu.shape
Out[744]: (1, 2, 2)
In [745]: new_path
Out[745]: 
array([[[0, 0],
        [1, 0],
        [2, 0]]])
In [746]: new_path.shape
Out[746]: (1, 3, 2)

您已经定义了2个数组,其形状为(1,2,2)和(1,3,2)。如果你对这些形状感到困惑,你需要重读一些基本的numpy介绍。

hstackvstackappend都叫concatenate。使用3d阵列使用它们只会让事情变得混乱。

连接在第二轴上,其中一个尺寸为2,另一个尺寸为3,用于生成(1,5,2)阵列。 (这相当于hstack

In [747]: np.concatenate((queu, new_path),axis=1)
Out[747]: 
array([[[0, 0],
        [0, 1],
        [0, 0],
        [1, 0],
        [2, 0]]])

尝试加入轴0(vstack)会产生错误:

In [748]: np.concatenate((queu, new_path),axis=0)
....
ValueError: all the input array dimensions except for the concatenation axis must match exactly

串联轴为0,但轴1的尺寸不同。因此错误。

您的目标不是有效的numpy数组。您可以在列表中一起收集它们:

In [759]: alist=[queu[0], new_path[0]]
In [760]: alist
Out[760]: 
[array([[0, 0],
        [0, 1]]), 
 array([[0, 0],
        [1, 0],
        [2, 0]])]

或者一个对象dtype数组 - 但这是更高级的numpy


1
投票

你需要的是np.hstack

In [73]: queu = np.array([[[0, 0],
                            [0, 1]]
                         ])
In [74]: queu.shape
Out[74]: (1, 2, 2)

In [75]: new_path = np.array([ [[0, 0],
                                [1, 0],
                                [2, 0]]
                             ])

In [76]: new_path.shape
Out[76]: (1, 3, 2)

In [81]: np.hstack((queu, new_path))
Out[81]: 
array([[[0, 0],
        [0, 1],
        [0, 0],
        [1, 0],
        [2, 0]]])

0
投票

我不完全清楚你是如何设置你的arrays的,但从它的声音来看,np.vstack确实应该做你想要的:

In [30]: queue = np.array([0, 0, 0, 1]).reshape(2, 2)

In [31]: queue
Out[31]:
array([[0, 0],
       [0, 1]])

In [32]: new_path = np.array([0, 0, 1, 0, 2, 0]).reshape(3, 2)

In [33]: new_path
Out[33]:
array([[0, 0],
       [1, 0],
       [2, 0]])

In [35]: np.vstack((queue, new_path))
Out[35]:
array([[0, 0],
       [0, 1],
       [0, 0],
       [1, 0],
       [2, 0]])
© www.soinside.com 2019 - 2024. All rights reserved.