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