检查numpy数组是否为多维数组

70

我想检查一个numpy数组是否为多维数组?

V = [[ -7.94627203e+01  -1.81562235e+02  -3.05418070e+02  -2.38451033e+02][  9.43740653e+01   1.69312771e+02   1.68545575e+01  -1.44450299e+02][  5.61599000e+00   8.76135909e+01   1.18959245e+02  -1.44049237e+02]]

我该如何在numpy中实现这个?

3个回答

125

使用ndarray的 .ndim 属性:

>>> a = np.array([[ -7.94627203e+01,  -1.81562235e+02,  -3.05418070e+02,  -2.38451033e+02],[  9.43740653e+01,   1.69312771e+02,   1.68545575e+01,  -1.44450299e+02],[  5.61599000e+00,   8.76135909e+01,   1.18959245e+02,  -1.44049237e+02]])
>>> a.ndim
2

7
在某些情况下,您还应该添加 np.squeeze() 以确保没有 "空" 维度。
>>> a = np.array([[1,2,3]])
>>> a.ndim
2
>>> a = np.squeeze(a)
>>> a .ndim
1

0
你也可以使用 .shape 属性,它会返回一个元组,其中包含每个维度的长度。因此,要使用 .shape 获取维度,你也可以在结果元组上调用 len()
import numpy as np

a = np.array([1,2,3])
b = np.array([[1,2,3]])
c = np.array([[1,2,3],[2,4,6],[3,6,9]])

print("a={}".format(a))
print("a.shape: {}; len(a.shape): {}".format(a.shape, len(a.shape)))

print("b={}".format(b))
print("b.shape: {}; len(b.shape): {}".format(b.shape, len(b.shape)))

print(c)
print("c.shape: {}; len(c.shape): {}".format(c.shape, len(c.shape)))

输出:

a=[1 2 3]
a.shape: (3,); len(a.shape): 1
b=[[1 2 3]]
b.shape: (1, 3); len(b.shape): 2
[[1 2 3]
 [2 4 6]
 [3 6 9]]
c.shape: (3, 3); len(c.shape): 2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接