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).
Eg 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]
You can do this using map_coordinates
. Here is a small example for a 3x3x3 volume:
a = np.arange(27).reshape(3,3,3)
xi,yi = np.meshgrid(range(3),range(3))
zi = xi*.25+yi*.25
inds = np.array([xi.reshape(1,9),yi.reshape(1,9),zi.reshape(1,9)])
ndimage.map_coordinates(a,inds).reshape(3,3)
>> array([[ 0, 9, 18],
[ 3, 12, 22],
[ 6, 16, 25]])
Note there may be a better way to do this without all the reshaping.
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]]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.