2016-08-09 57 views
4

我遇到np.append問題。ValueError:所有輸入數組必須具有相同的維數

我嘗試使用下面的代碼複製20x361矩陣n_list_converted的最後一列:

n_last = [] 
n_last = n_list_converted[:, -1] 
n_lists = np.append(n_list_converted, n_last, axis=1) 

,但我得到的錯誤:

ValueError: all the input arrays must have same number of dimensions

不過,我已經檢查矩陣尺寸做

print(n_last.shape, type(n_last), n_list_converted.shape, type(n_list_converted)) 

,我也得到

(20L,) (20L, 361L)

所以尺寸匹配?錯誤在哪裏?

+5

嘗試'np.column_stack'。 – Divakar

+2

它的工作!但爲什麼? – odo22

回答

5

如果我和3×4陣列開始,並連接一個3×1陣列,其中軸1,得到了一個3×5陣列:

In [911]: x = np.arange(12).reshape(3,4) 
In [912]: np.concatenate([x,x[:,-1:]], axis=1) 
Out[912]: 
array([[ 0, 1, 2, 3, 3], 
     [ 4, 5, 6, 7, 7], 
     [ 8, 9, 10, 11, 11]]) 
In [913]: x.shape,x[:,-1:].shape 
Out[913]: ((3, 4), (3, 1)) 

注意,兩個輸入端以連接有2種尺寸。

略去:,和x[:,-1]是(3,)形狀 - 這是一維,並因此錯誤:

In [914]: np.concatenate([x,x[:,-1]], axis=1) 
... 
ValueError: all the input arrays must have same number of dimensions 

np.append的代碼(在這種情況下被指定的軸)

return concatenate((arr, values), axis=axis) 

所以隨着語法的輕微變化append的作品。而不是一個列表,它需要2個參數。它模仿列表append是語法,但不應該與列表方法混淆。

In [916]: np.append(x, x[:,-1:], axis=1) 
Out[916]: 
array([[ 0, 1, 2, 3, 3], 
     [ 4, 5, 6, 7, 7], 
     [ 8, 9, 10, 11, 11]]) 

np.hstack首先確保所有的輸入都atleast_1d,然後它串聯:

return np.concatenate([np.atleast_1d(a) for a in arrs], 1) 

所以它需要同x[:,-1:]輸入。基本上是同一個動作。

np.column_stack也做在軸上1.一個串連但首先通過它

array(arr, copy=False, subok=True, ndmin=2).T 

通過1D輸入本是轉動該(3)陣列劃分爲(3,1)陣列的一般方法。

In [922]: np.array(x[:,-1], copy=False, subok=True, ndmin=2).T 
Out[922]: 
array([[ 3], 
     [ 7], 
     [11]]) 
In [923]: np.column_stack([x,x[:,-1]]) 
Out[923]: 
array([[ 0, 1, 2, 3, 3], 
     [ 4, 5, 6, 7, 7], 
     [ 8, 9, 10, 11, 11]]) 

所有這些「堆棧」可以方便,但是從長遠來看,瞭解尺寸和基本np.concatenate是很重要的。也知道如何查找這樣的函數的代碼。我使用了很多魔術。

而在時間測試中,np.concatenate明顯更快 - 這樣一個小型數組,多餘的函數調用層次會產生很大的時間差異。

3

(n,)和(n,1)不是相同的形狀。嘗試使用[:, None]符號鑄造向量數組:

n_lists = np.append(n_list_converted, n_last[:, None], axis=1) 

另外,提取n_last時,你可以使用

n_last = n_list_converted[:, -1:] 

獲得(20, 1)陣列。

2

你得到你的錯誤的原因是因爲「1乘n」矩陣不同於長度爲n的數組。

我推薦使用hstack()vstack()來代替。 像這樣:

import numpy as np 
a = np.arange(32).reshape(4,8) # 4 rows 8 columns matrix. 
b = a[:,-1:]     # last column of that matrix. 

result = np.hstack((a,b))  # stack them horizontally like this: 
#array([[ 0, 1, 2, 3, 4, 5, 6, 7, 7], 
#  [ 8, 9, 10, 11, 12, 13, 14, 15, 15], 
#  [16, 17, 18, 19, 20, 21, 22, 23, 23], 
#  [24, 25, 26, 27, 28, 29, 30, 31, 31]]) 

通知重複 「7,圖15,23,31」 列中。 另外,請注意,我使用a[:,-1:]而不是a[:,-1]。我的版本生成列:

array([[7], 
     [15], 
     [23], 
     [31]]) 

取而代之的是一排array([7,15,23,31])


編輯:append()慢。閱讀this answer

+0

'np.append'比列表'.append'慢;但與「堆棧」相當。它使用'np.concatenate'。 – hpaulj

+0

@hpaulj所以...正如我所說的使用'append' vs'stack'與2個矩陣相同,'stack'對於超過2個元素是更好的,所以'stack'總是_至少與'append'一樣好'。 – RuRo

相關問題