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

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

当前回答

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

其他回答

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

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:

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是Numpy ndarray。但是Numpy也可以计算纯python对象的可迭代对象的形状:

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