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

2024-04-19 17:31:18 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑:

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

维度1如何?我已经给出了一个由三个变量组成的方程。这意味着它是三维的,但它显示的尺寸为1。ndim的逻辑是什么


Tags: importnumpy尺寸asnp逻辑array方程
1条回答
网友
1楼 · 发布于 2024-04-19 17:31:18

正如NumPy documentation所说,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返回一个tuple,您应该使用[0]获取维度

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

相关问题 更多 >