Python numpy 入門系列 12 數組操作(翻轉數組 )


翻轉數組

函數 描述
transpose 對換數組的維度;轉置
ndarray.T self.transpose() 相同;轉置
rollaxis 向后滾動指定的軸
swapaxes 對換數組的兩個軸

numpy.transpose

numpy.transpose 函數用於轉置,格式如下:

numpy.transpose(arr, axes)

參數說明:

  • arr:要操作的數組
  • axes:整數列表,對應維度,通常所有維度都會對換。

實例

import numpy as np a = np.arange(12).reshape(3,4) print ('原數組:') print (a ) print ('\n') print ('對換數組:') print (np.transpose(a))
輸出結果如下:
原數組: [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] 對換數組: [[ 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 ('原數組:') print (a) print ('\n') print ('轉置數組:') print (a.T)
輸出結果如下:
原數組: [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] 轉置數組: [[ 0 4 8] [ 1 5 9] [ 2 6 10] [ 3 7 11]]

 

numpy.rollaxis

numpy.rollaxis 函數向后滾動特定的軸到一個特定位置,格式如下:

numpy.rollaxis(arr, axis, start)

參數說明:

  • arr:數組
  • axis:要向后滾動的軸,其它軸的相對位置不會改變
  • start:默認為零,表示完整的滾動。會滾動到特定位置。

實例

import numpy as np # 創建了三維的 ndarray a = np.arange(8).reshape(2,2,2) print ('原數組:') print (a) print ('獲取數組中一個值:') print(np.where(a==6)) print(a[1,1,0]) # 為 6 print ('\n') # 將軸 2 滾動到軸 0(寬度到深度) print ('調用 rollaxis 函數:') b = np.rollaxis(a,2,0) print (b) # 查看元素 a[1,1,0],即 6 的坐標,變成 [0, 1, 1] # 最后一個 0 移動到最前面 print(np.where(b==6)) print ('\n') # 將軸 2 滾動到軸 1:(寬度到高度) print ('調用 rollaxis 函數:') c = np.rollaxis(a,2,1) print (c) # 查看元素 a[1,1,0],即 6 的坐標,變成 [1, 0, 1] # 最后的 0 和 它前面的 1 對換位置 print(np.where(c==6)) print ('\n')

 輸出結果如下:

原數組: [[[0 1] [2 3]] [[4 5] [6 7]]] 獲取數組中一個值: (array([1]), array([1]), array([0])) 6 調用 rollaxis 函數: [[[0 2] [4 6]] [[1 3] [5 7]]] (array([0]), array([1]), array([1])) 調用 rollaxis 函數: [[[0 2] [1 3]] [[4 6] [5 7]]] (array([1]), array([0]), array([1]))

numpy.swapaxes

numpy.swapaxes 函數用於交換數組的兩個軸,格式如下:

numpy.swapaxes(arr, axis1, axis2)
  • arr:輸入的數組
  • axis1:對應第一個軸的整數
  • axis2:對應第二個軸的整數

實例

import numpy as np # 創建了三維的 ndarray a = np.arange(8).reshape(2,2,2) print ('原數組:') print (a) print ('\n') # 現在交換軸 0(深度方向)到軸 2(寬度方向) print ('調用 swapaxes 函數后的數組:') print (np.swapaxes(a, 2, 0))

輸出結果如下:

原數組: [[[0 1] [2 3]] [[4 5] [6 7]]] 調用 swapaxes 函數后的數組: [[[0 4] [2 6]] [[1 5] [3 7]]]


REF

https://blog.csdn.net/liaoyuecai/article/details/80193996

https://zhuanlan.zhihu.com/p/162874970

https://www.pythonheidong.com/blog/article/327410/5081b117d3e63a119c98/

https://www.cnblogs.com/mzct123/p/8659193.html  (numpy flatten ravel)
https://blog.csdn.net/weixin_43960668/article/details/114979389 (numpy flatten ravel)

https://www.runoob.com/numpy/numpy-array-manipulation.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM