> 文章列表 > numpy中transpose详解

numpy中transpose详解

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).T achieves this, as does a[:, 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, then transpose(a).shape == a.shape[::-1].

2. 参数说明

axes tuple or list of ints, optional

If specified, it must be a tuple or list which contains a permutation of [0,1,…,N-1] where N is the number of axes of a. The i’th axis of the returned array will correspond to the axis numbered axes[i] of the input. If not specified, defaults to range(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 Manual

numpy数组的转置与换轴transpose和swapaxes方法_Everglow_Vct的博客-CSDN博客