python – 在numpy中工作的ndim [复制]

参见英文答案 >
working of ndim in numpy                                    1个

import numpy as np
>>> a=np.array([1,2,3,4])
>>> a
array([1, 2, 3, 4])
>>> a.ndim
1

尺寸如何为1.我给出了3个变量的等式,这意味着它是3维,但是它将尺寸显示为1.谁能告诉我ndim的逻辑?

最佳答案 正如
numpy docs所说,numpy.ndim(a)返回:

The number of dimensions in a. Scalars are zero-dimensional

例如.:

a = np.array(111)
b = np.array([1,2])
c = np.array([[1,2], [4,5]])
d = np.array([[1,2,3,], [4,5]])
print a.ndim, b.ndim, c.ndim, d.ndim
#outputs: 0 1 2 1

请注意,最后一个数组d是对象dtype的数组,因此它的维度仍为1.

你想要使用的是a.shape(或一维数组的a.size):

print a.size, b.size
print c.size # == 4, which is the total number of elements in the array
#outputs:
1 2
4

方法.shape返回一个元组,你应该使用[0]得到你的维度:

print a.shape, b.shape, b.shape[0]
() (2L,) 2
点赞