arr = np.arange(10).reshape(2, 5)
使用.transpose方法:
arr.transpose() # Out: # array([[0, 5], # [1, 6], # [2, 7], # [3, 8], # [4, 9]])
.T 方法:
arr.T # Out: # array([[0, 5], # [1, 6], # [2, 7], # [3, 8], # [4, 9]])
或np.transpose:
np.transpose(arr) # Out: # array([[0, 5], # [1, 6], # [2, 7], # [3, 8], # [4, 9]])
在二维数组的情况下,这等效于标准矩阵转置(如上所述)。在n维情况下,可以指定阵列轴的排列。默认情况下,这是相反的array.shape:
a = np.arange(12).reshape((3,2,2)) a.transpose() # equivalent to a.transpose(2,1,0) # Out: # array([[[ 0, 4, 8], # [ 2, 6, 10]], # # [[ 1, 5, 9], # [ 3, 7, 11]]])
但是轴索引的任何排列都是可能的:
a.transpose(2,0,1) # Out: # array([[[ 0, 2], # [ 4, 6], # [ 8, 10]], # # [[ 1, 3], # [ 5, 7], # [ 9, 11]]]) a = np.arange(24).reshape((2,3,4)) # shape (2,3,4) a.transpose(2,0,1).shape # Out: # (4, 2, 3)