np.hstack與np.vstack
阿新 • • 發佈:2018-12-21
np.hstack(tup)
tup: The arrays must have the same shape along all but the second axis, except 1-D arrays which can be any length.
tup: 二維陣列需要第一個維度相同;但是一維陣列可以是任意長度
這是一個連線函式,將多個數組沿著水平方向連線(即對第2個維度進行連線)
二維陣列連線的程式碼如下:
>>> a = np.array([[1],[2], [3]]) >>> b = np.array([[1,11],[2,22], [3,33]]) >>> a.shape (3, 1) >>> b.shape (3, 2) >>> np.hstack((a,b)) array([[ 1, 1, 11], [ 2, 2, 22], [ 3, 3, 33]])
一維陣列連線的程式碼如下:
>>> np.hstack(([1,2], [3,4,5,6,7,8]))
array([1, 2, 3, 4, 5, 6, 7, 8])
注意:
不能將二維陣列和一維陣列進行連線,必須保證他們具有的維度個數相同;
多個數組應用元組()表示;
示例如下:
>>> np.hstack(([1,2], [[3],[4]])) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/zhujun/anaconda3/lib/python3.6/site-packages/numpy/core/shape_base.py", line 286, in hstack return _nx.concatenate(arrs, 0) ValueError: all the input arrays must have same number of dimensions
np.vstack(tup)
The arrays must have the same shape along all but the first axis. 1-D arrays must have the same length.
tup: 二維陣列需要第二個維度相同;但是一維陣列必須長度相同
這是一個連線函式,將多個數組沿著垂直方向連線(即對第1個維度進行連線)
二維陣列連線如下:
>>> a = np.array([[1,2]]) >>> b = np.array([[11,22],[33,44]]) >>> a.shape (1, 2) >>> b.shape (2, 2) >>> np.vstack((a,b)) array([[ 1, 2], [11, 22], [33, 44]])
一維陣列連線如下:
>>> np.vstack(([1,2], [3,4]))
array([[1, 2],
[3, 4]])