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

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

当前回答

使用.shape:

In: a = np.array([[1,2,3],[4,5,6]])
In: a.shape
Out: (2, 3)
In: a.shape[0] # x axis
Out: 2
In: a.shape[1] # y axis
Out: 3

其他回答

使用.shape:

In: a = np.array([[1,2,3],[4,5,6]])
In: a.shape
Out: (2, 3)
In: a.shape[0] # x axis
Out: 2
In: a.shape[1] # y axis
Out: 3

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

>>> a.shape
(2, 2)

在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]])
rows = a.shape[0] # 2 
cols = a.shape[1] # 2
a.shape #(2,2)
a.size # rows * cols = 4