python - 了解 NumPy 中的轴

标签 python numpy

我正在浏览 NumPy documentation ,并且我无法理解一点。对于下面的示例,它提到该数组的秩为 2(它是二维的)。第一个维度(轴)的长度为 2,第二个维度的长度为 3。

 [[ 1., 0., 0.],
 [ 0., 1., 2.]]

第一个维度(轴)的长度如何为 2?

编辑: 我感到困惑的原因是文档中的以下声明。

The coordinates of a point in 3D space [1, 2, 1] is an array of rank 1, because it has one axis. That axis has a length of 3.

在原始的 2D ndarray 中,我假设列表的数量标识了等级/维度,并且我错误地假设每个列表的长度表示每个维度的长度(按该顺序)。因此,根据我的理解,第一个维度的长度应该为 3,因为第一个列表的长度是 3。

最佳答案

numpy ,轴顺序如下 zyx约定,而不是通常的(也许更直观)xyz .

从视觉上看,这意味着对于水平轴为 x 的二维数组纵轴是y :

    x -->
y      0   1   2
|  0 [[1., 0., 0.],
V  1  [0., 1., 2.]]

shape该数组的值为 (2, 3)因为它是订购的(y, x) ,第一个轴 y长度2 .

并通过切片验证这一点:

import numpy as np

a = np.array([[1, 0, 0], [0, 1, 2]], dtype=np.float)

>>> a
Out[]:
array([[ 1.,  0.,  0.],
       [ 0.,  1.,  2.]])

>>> a[0, :]                    # Slice index 0 of first axis
Out[]: array([ 1.,  0.,  0.])  # Get values along second axis `x` of length 3

>>> a[:, 2]                    # Slice index 2 of second axis
Out[]: array([ 0.,  2.])       # Get values along first axis `y` of length 2

关于python - 了解 NumPy 中的轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46855793/

相关文章:

python - 根据可用的库执行代码

c++ - 定义类时执行什么代码?

python - 将 header 添加到 Numpy 数组

Python RuntimeWarning 在 double_scalars 中遇到溢出

numpy - 使用值数组将 numpy 分组为多个子数组

python - 使用 2D 掩码和整个矩阵运算索引的 3D 或 4D Numpy 数组

python - 匹配 EmbeddedDocumentList 中的 EmbeddedDocument

python - ndarray array2string 输出格式

python - 我应该在哪里放置 try/except block 的 return 语句?

python - numpy 3D meshgrid 仅作为 View