常見的數(shù)組翻轉(zhuǎn)等方法
| 函數(shù) | 描述 |
| transpose | 對換數(shù)組的維度 |
| ndarray.T | 和 self.transpose() 相同 |
| rollaxis | 向后滾動指定的軸 |
| swapaxes | 對換數(shù)組的兩個軸 |
numpy.transpose 函數(shù)用于對換數(shù)組的維度,格式如下:
numpy.transpose(arr, axes)
參數(shù)說明:
arr:要操作的數(shù)組axes:整數(shù)列表,對應維度,通常所有維度都會對換。
import numpy as np
a = np.arange(12).reshape(3,4)
print ('原數(shù)組:')
print (a )
print ('\n')
print ('對換數(shù)組:')
print (np.transpose(a))輸出結(jié)果如下:
原數(shù)組: [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] 對換數(shù)組: [[ 0 4 8] [ 1 5 9] [ 2 6 10] [ 3 7 11]]
numpy.ndarray.T 類似 numpy.transpose:
import numpy as np
a = np.arange(12).reshape(3,4)
print ('原數(shù)組:')
print (a)
print ('\n')
print ('轉(zhuǎn)置數(shù)組:')
print (a.T)輸出結(jié)果如下:
原數(shù)組: [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] 轉(zhuǎn)置數(shù)組: [[ 0 4 8] [ 1 5 9] [ 2 6 10] [ 3 7 11]]
numpy.rollaxis 函數(shù)向后滾動特定的軸到一個特定位置,格式如下:
numpy.rollaxis(arr, axis, start)
參數(shù)說明:
arr:數(shù)組axis:要向后滾動的軸,其它軸的相對位置不會改變start:默認為零,表示完整的滾動。會滾動到特定位置。
import numpy as np
# 創(chuàng)建了三維的 ndarray
a = np.arange(8).reshape(2,2,2)
print ('原數(shù)組:')
print (a)
print ('\n')
# 將軸 2 滾動到軸 0(寬度到深度)
print ('調(diào)用 rollaxis 函數(shù):')
print (np.rollaxis(a,2))
# 將軸 0 滾動到軸 1:(寬度到高度)
print ('\n')
print ('調(diào)用 rollaxis 函數(shù):')
print (np.rollaxis(a,2,1))輸出結(jié)果如下:
原數(shù)組: [[[0 1] [2 3]] [[4 5] [6 7]]] 調(diào)用 rollaxis 函數(shù): [[[0 2] [4 6]] [[1 3] [5 7]]] 調(diào)用 rollaxis 函數(shù): [[[0 2] [1 3]] [[4 6] [5 7]]]
numpy.swapaxes 函數(shù)用于交換數(shù)組的兩個軸,格式如下:
numpy.swapaxes(arr, axis1, axis2)
arr:輸入的數(shù)組axis1:對應第一個軸的整數(shù)axis2:對應第二個軸的整數(shù)
import numpy as np
# 創(chuàng)建了三維的 ndarray
a = np.arange(8).reshape(2,2,2)
print ('原數(shù)組:')
print (a)
print ('\n')
# 現(xiàn)在交換軸 0(深度方向)到軸 2(寬度方向)
print ('調(diào)用 swapaxes 函數(shù)后的數(shù)組:')
print (np.swapaxes(a, 2, 0))輸出結(jié)果如下:
原數(shù)組: [[[0 1] [2 3]] [[4 5] [6 7]]] 調(diào)用 swapaxes 函數(shù)后的數(shù)組: [[[0 4] [2 6]] [[1 5] [3 7]]]