1、np.vstack() :垂直合併 2、np.hstack():水平合併 3、np.newaxis():轉置 4、np.concatenate():針對多個矩陣或序列的合併操作 ...
1、np.vstack() :垂直合併
>>> import numpy as np >>> A = np.array([1,1,1]) >>> B = np.array([2,2,2]) >>> print(np.vstack((A,B))) # vertical stack,屬於一種上下合併,即對括弧中的兩個整體進行對應操作 [[1 1 1] [2 2 2]] >>> C = np.vstack((A,B)) >>> print(A.shape,C.shape) (3,) (2, 3)
2、np.hstack():水平合併
>>> D = np.hstack((A,B)) # horizontal stack,即左右合併 >>> print(D) [1 1 1 2 2 2] >>> print(A.shape,D.shape) (3,) (6,)
3、np.newaxis():轉置
>>> print(A[np.newaxis,:]) [[1 1 1]] >>> print(A[np.newaxis,:].shape) (1, 3) >>> print(A[:,np.newaxis]) [[1] [1] [1]] >>> print(A[:,np.newaxis].shape) (3, 1) >>> A = np.array([1,1,1])[:,np.newaxis] >>> B = np.array([2,2,2])[:,np.newaxis] >>> C = np.vstack((A,B)) # vertical stack >>> D = np.hstack((A,B)) # horizontal stack >>> print(D) [[1 2] [1 2] [1 2]] >>> print(A.shape,D.shape) (3, 1) (3, 2)
4、np.concatenate():針對多個矩陣或序列的合併操作
#axis參數很好的控制了矩陣的縱向或是橫向列印,相比較vstack和hstack函數顯得更加 >>> C = np.concatenate((A,B,B,A),axis=0) >>> print(C) [[1] [1] [1] [2] [2] [2] [2] [2] [2] [1] [1] [1]] >>> D = np.concatenate((A,B,B,A),axis=1) >>> print(D) [[1 2 2 1] [1 2 2 1] [1 2 2 1]]