如果我和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
明顯更快 - 這樣一個小型數組,多餘的函數調用層次會產生很大的時間差異。
嘗試'np.column_stack'。 – Divakar
它的工作!但爲什麼? – odo22