1. 程式人生 > >np.vstack, np.hstack

np.vstack, np.hstack

np.vstack(tup)使用

沿著豎直方向將矩陣堆疊起來。
Note: the arrays must have the same shape along all but the first axis. 除開第一維外,被堆疊的矩陣各維度要一致。
示例程式碼:

import numpy as np

arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
res = np.vstack((arr1, arr2))

結果如下

array([[1, 2, 3],
       [4, 5, 6]])

np.hstack(tup)

沿著水平方向將陣列堆疊起來。
Note:
tup : sequence of ndarrays
All arrays must have the same shape along all but the second axis.
示例程式碼:

import numpy as np

arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
res = np.hstack((arr1, arr2))

print res


arr1 = np.array([[1, 2], [3, 4], [5, 6]])
arr2 = np.array([[7, 8], [9, 0], [0, 1]])
res = np.hstack((arr1, arr2))

print res

結果如下:

[1 2 3 4 5 6]

[[1 2 7 8]
 [3 4 9 0]
 [5 6 0 1]]