在numpy工作的ndim

时间:2015-01-16 05:51:40

标签: python numpy

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的逻辑?

1 个答案:

答案 0 :(得分:2)

正如numpy docs所说,numpy.ndim(a)返回:

  

a中的维度数量。标量是零维的

e.g:

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 object 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返回tuple,您应该使用[0]获取

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