NumPy 中 ndim 的真正作用是什么?

Rob*_*ela 4 python numpy

考虑:

import numpy as np
>>> a=np.array([1, 2, 3, 4])
>>> a
array([1, 2, 3, 4])
>>> a.ndim
1
Run Code Online (Sandbox Code Playgroud)

维度1如何?我给出了三个变量的方程。意思是它是三维的,但它显示的维度为1。ndim的逻辑是什么?

zha*_*hen 5

正如NumPy 文档所述,numpy.ndim(a)返回:

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

例如:

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
Run Code Online (Sandbox Code Playgroud)

请注意,最后一个数组是一个对象d数组,因此它的维度仍然是。 dtype1

您想要使用的可能是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
Run Code Online (Sandbox Code Playgroud)

方法.shape返回您 a tuple,您应该使用以下方法获取尺寸[0]

print a.shape, b.shape, b.shape[0]
() (2L,) 2
Run Code Online (Sandbox Code Playgroud)