BaRud
BaRud

Reputation: 3230

dimension not matching for a nd array

I have created an nd array from a file as:

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()]

Which I am expecting to be a 3d array(i,j,x). But its not. After converting it to a numpy array as:

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

yeilds: (250, 301) which is the dimension of i,j. But, in my think process, it is indeed 3d as:

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

yeilds: [-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]

What I am doing wrong here?

Upvotes: 0

Views: 256

Answers (1)

Nils Werner
Nils Werner

Reputation: 36839

Your nested lists are probably of different lengths, forcing NumPy to create an array of dtype=object, meaning an array of lists instead of floats.

compare

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')

and

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')

Upvotes: 1

Related Questions