简体   繁体   English

从多维numpy数组中选择

[英]Selecting from multidimensional numpy array

I have a multidimensional array a with shape (nt, nz, ny, nx). 我有一个多维数组a形状(nt,nz,ny,nx)。 The dimensions are time, z, y, x. 尺寸是时间,z,y,x。 For each time, x and y, I've selected the appropriate z in a new index array J with shape (nt, ny, nx). 对于x和y的每一次,我在具有形状(nt,ny,nx)的新索引数组J中选择了适当的z。 J contains the indices along the height dimension that I'd like to select. J包含我想要选择的高度维度的索引。 Using Python, I could do this in a loop: 使用Python,我可以在循环中执行此操作:

b=J.copy()
for t in range(nt):
   for y in range(ny):
      for x in range(nx):
         z=J[t,y,x]
         b[t,y,x]=a[t,z,y,x]

But I want to do this faster, without the loops. 但我想更快地完成这项工作,没有循环。 This is probably trivial, but I can't get my head around it. 这可能是微不足道的,但我无法理解它。 Anyone? 任何人?

You can use numpy.indices() together with advanced indexing: 您可以将numpy.indices()与高级索引一起使用:

t, y, x = numpy.indices(J.shape)
b = a[t, J, y, x]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM