Reputation: 354
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.
Upvotes: 0
Views: 37
Reputation: 12157
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
Upvotes: 2