Scott Alistair Scott Alistair - 6 months ago 28
Python Question

Easiest way to slice border particles in a 3D numpy array with variable border size

Ok, so I am dealing with large 3D numpy arrays, I want to find the easiest way to set all the border values in the array (of size b) to zero...

So for example I have a filled 3D numpy array called labelled, at the moment I have something like this...

labelled[[0,1,2,..b,-1,-2,-3,..-b],:,:] = 0
labelled[:,[0,1,2,..b,-1,-2,-3,..-b],:] = 0
labelled[:,:,[0,1,2,..b,-1,-2,-3,..-b]] = 0


This method requires me literally changing and writing in all the values inbetween 0-b everytime I change the value of b which is very impractical...

I've tried things like...

labelled[([0:b],[-1:-b]),:,:] = 0
labelled[:,([0:b],[-1:-b]),:] = 0
labelled[:,:,([0:b],[-1:-b])] = 0


and...

labelled[[-b:b],:,:] = 0
labelled[:,[-b:b],:] = 0
labelled[:,:,[-b:b]] = 0


but they don't work.

Open to any suggestions guys, thank you

Answer

This seems to work:

x[0:b, :, :] = 0
x[-b:, :, :] = 0
x[:, 0:b, :] = 0
x[:, -b:, :] = 0
x[:, :, 0:b] = 0
x[:, :, -b:] = 0
Comments