Numpy 数组维度

新手上路,请多包涵

如何获取数组的维度?例如,这是 2x2:

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

原文由 morgan freeman 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 994
2 个回答

使用 .shape 获取数组维度的元组:

 >>> a.shape
(2, 2)

原文由 Felix Kling 发布,翻译遵循 CC BY-SA 4.0 许可协议

第一的:

按照惯例,在 Python 世界中, numpy 的快捷方式是 np ,所以:

 In [1]: import numpy as np

In [2]: a = np.array([[1,2],[3,4]])

第二:

在 Numpy 中, dimensionaxis/axesshape 是相关的,有时是相似的概念:

尺寸

数学/物理 中,维度或维数被非正式地定义为指定空间内任何点所需的最小坐标数。但在 Numpy 中,根据 numpy 文档,它与轴/轴相同:

在 Numpy 中维度被称为轴。轴的数量是等级。

 In [3]: a.ndim  # num of dimensions/axes, *Mathematics definition of dimension*
Out[3]: 2

轴/轴

在 Numpy 中索引 array第 n 个 坐标。多维数组每个轴可以有一个索引。

 In [4]: a[1,0]  # to index `a`, we specific 1 at the first axis and 0 at the second axis.
Out[4]: 3  # which results in 3 (locate at the row 1 and column 0, 0-based index)

形状

描述每个可用轴上有多少数据(或范围)。

 In [5]: a.shape
Out[5]: (2, 2)  # both the first and second axis have 2 (columns/rows/pages/blocks/...) data

原文由 YaOzI 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题