python 學習筆記(1)--numpy數組轉置__python

來源:互聯網
上載者:User

關於數組的轉置,Numpy提供了transpose函數和.T屬性兩種實現形式,一般transpose使用起來更為方便,另外轉換其中的兩個軸還可以用swapreaxes,下面通過例子來做介紹。

#一維數組轉置>>> arr = np.arange(6)>>> print arr[0, 1, 2, 3, 4, 5]>>> print np.transpose(arr)[0, 1, 2, 3, 4, 5]#一維還是一維…#二維數組轉置>>> arr = np.arange(6).reshape((2,3))>>> print arr[[0, 1, 2], [3, 4, 5]]>>> print np.transpose(arr)[[0,3], [1,4], [3,5]]#三維數組的轉置>>> arr = np.arange(24).reshape((2,3,4))>>> print arr[[[ 0, 1, 2, 3],   [ 4, 5, 6, 7],   [ 8, 9, 10, 11]],  [[ 12, 13, 14, 15],   [ 16, 17, 18, 19],   [ 20, 21, 22, 23]]]>>> print np.transpose(arr)[[[0, 12],  [4, 16],  [8, 20]], [[1, 13],  [5, 17],  [9, 21]], [[2, 14],  [6, 18],  [10, 22]], [[3, 15],  [7, 19],  [11, 23]]]#當數組>=三維之後,我們可能希望按照特定規則來轉置,transpose 可以接受用於指定轉置的座標軸號碼的元組>>> print np.transpose(arr, (1,0,2))[[[ 0, 1, 2, 3],  [ 12, 13, 14, 15]], [[ 4, 5, 6, 7],  [ 16, 17, 18, 19]], [[ 8, 9, 10, 11],  [ 20, 21, 22, 23]]]

對於是否指定轉化規則,具體來看三維的變化:未經處理資料的“三維”是(2,3,4),不指定轉換規則後的“三維”是(4,3,2),而指定規則後的三維則是按照我們指定的規則,將其一維和二維進行調換。

#原始三維資料規則>>> print (arr.shape)(2, 3, 4)#不指定轉換規則>>> print (np.transpose(arr).shape)(4, 3, 2)#指定轉換規則>>> print (np.transpose(arr,(1, 0, 2)).shape)(3, 2, 4)

ndarray的T屬性,用法則比較簡單,只需要在數組後跟.T即可。.T屬性實際是轉置裡面的特殊情況,即不指定轉置規則的預設規則。

#一維數組轉置>>> arr = np.arange(6)>>> print arr[0, 1, 2, 3, 4, 5]>>> print arr.T[0, 1, 2, 3, 4, 5]#一維還是一維…#二維數組轉置>>> arr = np.arange(6).reshape((2,3))>>> print arr[[0, 1, 2], [3, 4, 5]]>>> print arr.T[[0,3], [1,4], [3,5]]#三維數組的轉置>>> arr = np.arange(24).reshape((2,3,4))>>> print arr[[[ 0, 1, 2, 3],   [ 4, 5, 6, 7],   [ 8, 9, 10, 11]],  [[ 12, 13, 14, 15],   [ 16, 17, 18, 19],   [ 20, 21, 22, 23]]]>>> print arr.T[[[0, 12],  [4, 16],  [8, 20]], [[1, 13],  [5, 17],  [9, 21]], [[2, 14],  [6, 18],  [10, 22]], [[3, 15],  [7, 19],  [11, 23]]]

當某些情況下,你可能只需要轉換其中的兩個軸,除了可以使用transpose指定軸以外(當然需要每個軸都指定順便,只是調整其中的部分而已),還可以使用swapreaxes。

>>> arr = np.arange(24).reshape((2,3,4))>>> print arr[[[ 0, 1, 2, 3],   [ 4, 5, 6, 7],   [ 8, 9, 10, 11]],  [[ 12, 13, 14, 15],   [ 16, 17, 18, 19],   [ 20, 21, 22, 23]]]>>> print arr.swapaxes(1, 0)[[[ 0, 1, 2, 3],  [ 12, 13, 14, 15]], [[ 4, 5, 6, 7],  [ 16, 17, 18, 19]], [[ 8, 9, 10, 11],  [ 20, 21, 22, 23]]]

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.