NumPy 中 transpose 详解

张开发
2026/4/14 17:52:13 15 分钟阅读

分享文章

NumPy 中 transpose 详解
transpose 用于 NumPy 中高维度数组的轴变换在二维情况下就是通常说的转置。该方法很不好理解本文详细介绍该方法。该方法有两个实现分别是numpy.ndarray.transpose和numpy.transpose两者分别是类成员方法和独立的方法接口定义和功能和基本一致。1. 函数介绍For a 1-D array, this returns an unchanged view of the original array, as a transposed vector is simply the same vector.To convert a 1-D array into a 2-D column vector, an additional dimension must be added, e.g.,np.atleast2d(a).Tachieves this, as doesa[:, np.newaxis].For a 2-D array, this is the standard matrix transpose.For an n-D array, if axes are given, their order indicates how the axes are permuted (see Examples). If axes are not provided, thentranspose(a).shape a.shape[::-1].2. 参数说明axestuple or list of ints, optionalIf specified, it must be a tuple or list which contains a permutation of [0,1,…,N-1] where N is the number of axes ofa. Thei’th axis of the returned array will correspond to the axis numberedaxes[i]of the input. If not specified, defaults torange(a.ndim)[::-1], which reverses the order of the axes.3. 使用示例定义数组arr3d np.arange(16).reshape((2, 2, 4))结果array([[[ 0, 1, 2, 3],[4, 5, 6, 7]],[[8, 9, 10, 11],[12, 13, 14, 15]]])换轴操作arr3d.transpose((1, 0, 2))结果array([[[0, 1, 2, 3],[8, 9, 10, 11]],[[4, 5, 6, 7],[12, 13, 14, 15]]])说明例子中是一个三维的数组进行了轴变换arr3d的默认轴顺序是 (0, 1, 2) 而通过transpose方法换为了 (1, 0, 2)所以对应的空间中的位置也发生了变换。运行结果只是编译器对于三维数组的一种表达形式如果单纯的理解为只是将二三行互换了就很难理解这个方法。参考文献numpy.transpose — NumPy v1.24 Manualnumpy数组的转置与换轴transpose和swapaxes方法_Everglow_Vct的博客-CSDN博客

更多文章