2016-12-24 99 views
0

我開始使用NumPy。NumPy堆棧或將數組追加到數組

給定兩個np.array S,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)) 

但兩者都提高

all the input array dimensions except for the concatenation axis must match exactly

我沒有得到NumPy的理念。我究竟做錯了什麼?

+0

您所需的結果不是矩陣,因爲矩陣需要在所有軸上具有相同數量的元素(例如3x2-3行,每行只有2個元素) – sirfz

+0

好的,我明白了。我嘗試在2D矩陣上列舉所有可能的方法。我會改變我的方法。 –

回答

0

這並不完全清楚,我你如何設置array S,但是從它的聲音,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]]) 
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]]]) 
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,另一個軸爲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]])] 

或對象數組D型 - 但是這是更高級的numpy