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

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

当前回答

在python笔记本中执行以下代码块。

import numpy as np
a = np.array([[1,2],[1,2]])
print(a.shape)
print(type(a.shape))
print(a.shape[0])

输出

(2, 2)

<类的元组>

2

然后你意识到a.shape是一个元组。 所以你可以通过a.shape[维度索引]得到任何维度的大小

其他回答

shape方法要求a是Numpy ndarray。但是Numpy也可以计算纯python对象的可迭代对象的形状:

np.shape([[1,2],[1,2]])

第一:

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

In [1]: import numpy as np

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

第二:

在Numpy中,尺寸、轴/轴、形状是相关的,有时是相似的概念:

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

在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

你可以用.ndim表示尺寸,用.shape来知道确切的尺寸:

>>> var = np.array([[1,2,3,4,5,6], [1,2,3,4,5,6]])

>>> var.ndim
2

>>> varshape
(2, 6) 

你可以使用.重塑函数改变尺寸:

>>> var_ = var.reshape(3, 4)

>>> var_.ndim
2

>>> var_.shape
(3, 4)

在python笔记本中执行以下代码块。

import numpy as np
a = np.array([[1,2],[1,2]])
print(a.shape)
print(type(a.shape))
print(a.shape[0])

输出

(2, 2)

<类的元组>

2

然后你意识到a.shape是一个元组。 所以你可以通过a.shape[维度索引]得到任何维度的大小

rows = a.shape[0] # 2 
cols = a.shape[1] # 2
a.shape #(2,2)
a.size # rows * cols = 4