Numpy数组维度

438 投票
10 回答
1048407 浏览
提问于 2025-04-16 00:06

我该如何获取一个数组的维度呢?比如说,这个数组是2x2的:

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

10 个回答

49
import numpy as np   
>>> np.shape(a)
(2,2)

如果输入不是一个numpy数组,而是一个列表的列表,这个方法也能用。

>>> a = [[1,2],[1,2]]
>>> np.shape(a)
(2,2)

或者是一个元组的元组。

>>> a = ((1,2),(1,2))
>>> np.shape(a)
(2,2)
93

第一部分:

在Python的世界里,大家通常把numpy简写成np,所以:

In [1]: import numpy as np

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

第二部分:

在Numpy中,维度形状是相关的,有时候它们的意思也很相似:

维度

数学/物理中,维度通常是指在一个空间中,确定任何一点所需的最少坐标数。但在Numpy中,根据numpy文档,维度和轴是一样的:

在Numpy中,维度被称为轴。轴的数量叫做秩。

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

在Numpy中,第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
580

使用 .shape 可以获取数组的维度信息,返回一个元组。

>>> a.shape
(2, 2)

撰写回答