[英]Numpy slicing x,y,z array for variable z
I have a 3d array of position data, which I'd like to take 2-d
slices from. 我有位置数据,我想利用其中的3D阵列
2-d
从切片。 However the slices vary in the z
depth with x
(and y
eventually). 然而,切片的
z
深度随x
(和最终的y
)而变化。
Eg An array 100x100x100
, and I want the first slice to be the parallelogram starting at 例如,一个数组
100x100x100
,我希望第一个切片是从的平行四边形开始
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
. x=0,y=0 => x=100,y=100
,在x=0
时包含z
方向0-25
处的点,并且在x=100
时线性地变为z=25-50
。 So a sort of diagonal slice. 所以是一种对角切片。
Is there an efficient way to do this in numpy. 在numpy中有没有一种有效的方法来做到这一点。 Ideally something like
理想情况下
newarray = oldarray[z> x/100*25.0 && z < 25+x/100*25.0]
You can do this using map_coordinates
. 您可以使用
map_coordinates
执行此操作。 Here is a small example for a 3x3x3 volume: 以下是3x3x3卷的一个小示例:
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数组
xi
, yi
, zi
oldarray
会触发高级索引。 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将创建一个新的阵列,其形状与广播
xi
, yi
, zi
形成的阵列相同(所以在这种情况下,因为xi
是( xi
), yi
是( zi
), zi
是(100,100,25),输出为(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]]
Numpy然后使用
xi
, yi
和zi
(带广播)的相应元素填充该数组,以便newarray[i, j, k] = oldarray[xi[i, 0, 0], yi[0, j, 0], zi[i, j, k]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.