I have a 3d array of position data, which I'd like to take 2-d slices from. However the slices vary in the z depth with x (and y eventually).
E.g.
An array 100x100x100, and I want the first slice to be the parallelogram starting at
x=0,y=0 => x=100,y=100 containing the points in the z direction 0-25 when at x=0, and changing linearly to z=25-50 by the time x=100. So a sort of diagonal slice.
Is there an efficient way to do this in numpy. Ideally something like
newarray = oldarray[z> x/100*25.0 && z < 25+x/100*25.0]
Because your desired data will probably not be representable as a strided view of the original, you will have to use advanced indexing to pull out the coordinates you want.
c = np.r_[:100]
xi = c.reshape((100, 1, 1))
yi = c.reshape((1, 100, 1))
zi = np.empty((100, 100, 25), dtype=int)
for x in xrange(100):
for y in xrange(100):
zi[x,y] = np.arange(x*25/100, x*25/100+25) # or whatever other function
newarray = oldarray[xi, yi, zi]
Slicing oldarray using the numpy arrays xi, yi, zi triggers advanced indexing. Numpy will create a new array having the same shape as that formed by broadcasting xi, yi, zi (so in this case, since xi is (100, 1, 1), yi is (1, 100, 1), and zi is (100, 100, 25), the output will be (100, 100, 25)).
Numpy then fills that array using corresponding elements of xi, yi and zi (with broadcasting), so that newarray[i, j, k] = oldarray[xi[i, 0, 0], yi[0, j, 0], zi[i, j, k]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With