NumPy transpose()

transpose() 方法将给定数组的轴进行交换,这与数学中的矩阵转置类似。对于具有多于两个维度的数组,transpose() 会根据给定的参数来排列轴。

示例

import numpy as np

originalArray = np.array([[1, 2], [3, 4]])

# swaps the rows and columns of an array transposedArray = np.transpose(originalArray)
print(transposedArray) ''' Output: [[1 3] [2 4]] '''

transpose() 语法

transpose() 的语法是:

numpy.transpose(array, axes = None)

transpose() 参数

transpose() 方法接受两个参数:

  • array - 要转置的数组
  • axes(可选) - 转置矩阵的轴 ( tuplelist of integers )

transpose() 返回值

transpose() 方法返回一个轴已重新排列的 array


示例 1: 转置没有 axes 参数的数组

import numpy as np

originalArray = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# if axes argument is skipped, the shape of array is reversed transposedArray = np.transpose(originalArray)
print(transposedArray)

输出

[[1 4 7]
 [2 5 8]
 [3 6 9]]

转置二维 NumPy 数组与转置矩阵相同。


示例 2: 转置一维数组

如果我们在一个一维数组上使用 transpose() 方法,该方法将返回原始数组。

import numpy as np

originalArray = np.array([1, 2, 3, 4])

# try to swap the rows and columns of the given array transposedArray = np.transpose(originalArray)
print(transposedArray)

输出

 [1 2 3 4]

注意: transpose() 方法不能增加数组的维度。因此,该方法无法将一维行向量转换为列向量。


示例 3: 转置三维数组

axes 参数(第二个参数)定义了哪些轴被交换。

import numpy as np

originalArray = np.array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]])

# swap the rows and columns of the array based on given axes print('When axes are (2, 0, 1):') transposedArray = np.transpose(originalArray, (2, 0, 1))
print(transposedArray)
# swap the rows and columns of the array based on given axes print('When axes are (0, 2, 1):') transposedArray = np.transpose(originalArray, (0, 2, 1))
print(transposedArray)

输出

When axes are (2, 0, 1):
[[[0 2]
  [4 6]]

 [[1 3]
  [5 7]]]

When axes are (0, 2, 1):
[[[0 2]
  [1 3]]

 [[4 6]
  [5 7]]]

注意: NumPy 使用索引来表示维度,而不是像传统的 x、y、z 概念。维度表示为维度 0、维度 1,依此类推。

因此,axes 参数不能包含重复元素,因为一个维度只能出现一次。

1. 使用 (2, 0, 1) 作为 transpose() 的第二个参数

在原始数组中,(x, y, z) 分别由 (0, 1, 2) 表示。

如果我们使用 (2, 0, 1) 作为 transpose() 方法的第二个参数,它表示:

  • z 轴(索引 2)成为新的 x 轴
  • x 轴(索引 0)成为新的 y 轴
  • y 轴(索引 1)成为新的 z 轴

2. 使用 (0, 2, 1) 作为 transpose() 的第二个参数

如果我们使用 (0, 2, 1) 作为 transpose() 方法的第二个参数,它表示:

  • x 轴(索引 0)将保持不变
  • z 轴(索引 2)成为新的 y 轴
  • y 轴(索引 1)成为新的 z 轴

注意: 对于维度超过两个的数组,很难直观理解 transpose() 的工作原理。要了解更多信息,请访问 三维数组上 transpose() 的工作原理

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战