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

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

当前回答

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)

其他回答

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

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

a.shape只是np.info()的一个限定版本。看看这个:

import numpy as np
a = np.array([[1,2],[1,2]])
np.info(a)

Out

class:  ndarray
shape:  (2, 2)
strides:  (8, 4)
itemsize:  4
aligned:  True
contiguous:  True
fortran:  False
data pointer: 0x27509cf0560
byteorder:  little
byteswap:  False
type: int32

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

>>> a.shape
(2, 2)

使用.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

你可以用.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)