Reputation: 980
Similar questions have been asked on SO, but never in the form that I needed.
I seem to be having trouble understanding NumPy slicing behavior.
Lets say I have an Numpy Array of shape 512x512x120
vol1=some_numpy_array
print(x.shape) #result: (512,512,120)
I want to take a "z-slice" of this array, however I end up with a 512x120 array instead of a 512x512 one I try the following code for instance
zSlice=(vol1[:][:][2]).squeeze()
print(zSlice.shape()) #result: (512,120)
Why is the resulting array shape (512,120)
and not (512,512)
? How can I fix this problem?
Upvotes: 1
Views: 1475
Reputation: 18466
The problem with vol1[:][:][2]
is:
vol1[:]
will give the entire array, then again [:]
gives the entire array, and finally [2]
gives the array at index 2 to in the outer axis, eventually vol1[:][:][2]
is nothing but vol1[2]
which is not what you want.
You need to take numpy array slice:
vol1[:, :, 2].
Now, it will take all the items from outermost, and outer axes, but only item at index 2 for the inner most axis.
Upvotes: 1
Reputation: 71610
You have to slice at once:
vol1[:, :, 2].squeeze()
>>> vol1[:, :, 2].squeeze().shape
(512, 512)
Because doing [:]
repeatedly doesn't do anything:
>>> (vol1[:][:] == vol1).all()
True
>>>
It's because [:]
gets the whole of the list... doing it multiple times does not change anything.
Upvotes: 1