如何获取数组的维数?例如,这是2x2:
a = np.array([[1,2],[3,4]])
如何获取数组的维数?例如,这是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
其他回答
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)
在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.shape
(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