nd数组的维数不匹配

2024-10-04 03:18:58 发布

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

我已经从一个文件创建了一个nd数组,如下所示:

for i in range(int(atoms)):
    next(finp)
    for j in range(int(ldata[2])):
        aatom[i][j] = [float(x) for x in
                       finp.readline().strip().split()]

我希望它是一个3d数组(i,j,x)。但事实并非如此。将其转换为numpy数组后:

atom = np.array(aatom)
print(atom.shape)

是:(250, 301)这是i,j的维度。但是,在我的思考过程中,它确实是三维的:

print(atom[1][1][:])

是: [-3.995, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]

我做错什么了?你知道吗


Tags: inforreadlinerange数组floatnextint
1条回答
网友
1楼 · 发布于 2024-10-04 03:18:58

嵌套列表的长度可能不同,这迫使NumPy创建一个dtype=object数组,这意味着一个list数组而不是float

比较

a = [range(3), range(2)]  # different lenghts in inner lists
aa = np.array(a)
print aa
print aa.shape            # (2,)
print aa.dtype            # dtype('O')

以及

b = [range(3), range(3)]  # equal lenghts in inner lists
bb = np.array(b)
print bb
print bb.shape            # (2, 3)
print bb.dtype            # dtype('int64')

相关问题 更多 >