1

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?

Michael Sohnen
  • 953
  • 7
  • 15

2 Answers2

1

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.

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
  • I upvoted and accept, but it will only accept one, Both answer are basically the same, so I accepted the other one, since its first on my page – Michael Sohnen Aug 29 '21 at 10:25
  • Do you know why this indexing works when not slicing though (e.g. `vol1[x][y][z]`) ? – Michael Sohnen Aug 29 '21 at 10:26
  • @MichaelSohnen Because `[:]` slicing does not change the array, whereas if you do something like `[:2]` it would change the array, not only indexing :) – U13-Forward Aug 29 '21 at 10:27
1

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.

ThePyGuy
  • 17,779
  • 5
  • 18
  • 45
  • Thanks! This makes sense, but it seems strange, because when NOT slicing, the indexing works as expected `vol1[x][y][z]` will give the same value as `vol1[x,y,z]`. – Michael Sohnen Aug 29 '21 at 10:22
  • @MichaelSohnen, That is true, because `vol1[x][y][z]` works at one index at each axis so is same to `vol1[x,y,z]`, but `[:]` takes the entire array slice so is different. – ThePyGuy Aug 29 '21 at 10:26
  • I see now... the first and subsequent [:] each return a multidimensional array identical to the original in shape and value. I don't know why I thought numpy would unwrap one layer from the array for each [:], perhaps because this is what would happen with normal lists. – Michael Sohnen Aug 29 '21 at 10:28