7

Ihave a numpy array A like

A.shape
(512,270,1,20)

I dont want to use all the 20 layers in dimension 4. The new array should be like

Anew.shape
(512,270,1,2)

So I want to crop out 2 "slices" of the array A

refle
  • 587
  • 3
  • 6
  • 19

2 Answers2

10

From the python documentation, the answer is:

start = 4 # Index where you want to start.
Anew = A[:,:,:,start:start+2]
usernumber
  • 1,958
  • 1
  • 21
  • 58
Chiel
  • 6,006
  • 2
  • 32
  • 57
  • thanks, and if I dont want to crop a conected invervall but eg. the first, the 5th, the 11th ... slice? – refle Oct 20 '15 at 09:19
  • Read the excellent post http://stackoverflow.com/questions/509211/explain-pythons-slice-notation – Chiel Oct 20 '15 at 09:21
  • got it, thank you. just use [-1,-..,-..] to get to the slice – refle Oct 20 '15 at 09:27
  • 2
    See as well http://stackoverflow.com/questions/30856133/irregular-slicing-copying-in-numpy-array for irregular slicing. You can thus do `Anew = A[:,:,:,[1,4,5]]`. – Chiel Oct 20 '15 at 09:28
4

You can use a list or array of indices rather than slice notation in order to select an arbitrary sequence of indices in the final dimension:

x = np.zeros((512, 270, 1, 20))
y = x[..., [4, 10]] # the 5th and 11th indices in the final dimension
print(y.shape)
# (512,270,1,2)
ali_m
  • 71,714
  • 23
  • 223
  • 298