简体   繁体   中英

python3 numpy ndarray does not have consistant dimentions. Encountered odd behavor with shape atribute

I am using the numpy package in python 3. First, here is some code that shows the odd behavior I have encountered with the ndarray shape attribute.

threeDndarray = np.ndarray(shape=(2,5,2)) #3d ndarray to showcase behavor 
print(threeDndarray.shape)
**output:** (2, 5, 2)
print(threeDndarray[:][:][:].shape) 
**output:** (2, 5, 2)
#now the odd behavor
print(threeDndarray[:][1][:].shape) #expected (2,2) 
**output:** (5, 2) 
print(threeDndarray[:][:][1].shape)
**output:** (5, 2)
print(threeDndarray[1][:][:].shape)
**output:** (5, 2)

I believe this odd .shape behavior is related to the problem that I have. I want to store the values from five separate 2x2 matrices in a 3dndarray with the dimensions (2,5,2). I am unable to perform the operation my3dArray[:][i][:] = my2dMatrix, without getting an error related to dimension mismatching.

The specific error is

ValueError: could not broadcast input array from shape (2,2) into shape (5,2)

I do not understand why I am getting this error or why the shape attribute has such strange behavior.

You're not using numpy indexing correctly.

array[1]
array[:][1]
array[:][:][1]

are all the same operation (a view into array, then access index 1 of the first dimension) because (array[:] == array).all() is True . I think you mean

threeDndarray[1, :, :].shape
threeDndarray[:, 1, :].shape
threeDndarray[:, :, 1].shape    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM