numpy.rollaxis函數
阿新 • • 發佈:2018-11-27
pri .com shape 表示 分享 ret info style family
numpy.rollaxis
numpy.rollaxis 函數向後滾動特定的軸到一個特定位置,格式如下:
numpy.rollaxis(arr, axis, start)
參數說明:
arr
:數組axis
:要向後滾動的軸,其它軸的相對位置不會改變start
:默認為零,表示完整的滾動。會滾動到特定位置。
1 import numpy as np 2 3 # 創建了三維的 ndarray 4 a = np.arange(8).reshape(2,2,2) 5 6 print (‘原數組:‘) 7 print (a) 8 print (‘\n‘) 9 # 將軸 2 滾動到軸 0(寬度到深度)10 11 print (‘調用 rollaxis 函數:‘) 12 print (np.rollaxis(a,2)) 13 # 將軸 0 滾動到軸 1:(寬度到高度) 14 print (‘\n‘) 15 16 print (‘調用 rollaxis 函數:‘) 17 print (np.rollaxis(a,2,1))
輸出結果如下:
原數組: [[[0 1] [2 3]] [[4 5] [6 7]]] 調用 rollaxis 函數: [[[0 2] [4 6]] [[1 3] [5 7]]] 調用 rollaxis 函數: [[[0 2] [1 3]] [[4 6] [5 7]]]
分析:
創建的2x2x2是一個三維數組:[[[0, 1], [2, 3]], [[4, 5], [6, 7]]]
如果要取數值 2,則a[0][1][0] ,數組下標與值對應如下表:
0(000) | 1(001) |
2(010) | 3(011) |
4(100) | 5(101) |
6(110) | 7(111) |
程序運行np.rollaxis(a, 2)時,將軸2滾動到了軸0前面,即:5(101) ->6(110), 其他軸相對2軸位置不變(start默認0),數組下標排序由0,1,2變成了1,2,0
這時數組按下標順序重組,例如第一個數組中[0,1]下標為[000,001],其中0的下標變動不影響值,1位置的下標由001變成010,第一位的下標滾動到最後一位下標的後面,值由1(001)變成2(010):
0(000) ->0(000) | 1(001) ->2(010) |
2(010) ->4(100) | 3(011) ->6(110) |
4(100) ->1(001) | 5(101) ->3(011) |
6(110) ->5(101) | 7(111) ->7(111) |
numpy.rollaxis函數