在Numpy中使用2d数组对3d数组进行切片

问题描述 投票:1回答:1

我有一个关于使用2d数组切片3d数组的问题。largearray是3d数组,我想使用2d smallarray中的值进行切片

    array([[[36.914   , 38.795   , 37.733   , 36.68    , 35.411003,
     33.494   , 36.968002, 39.902   , 43.943   , 48.398   ],
    [37.121   , 38.723   , 37.706   , 36.653   , 35.491997,
     33.638   , 36.697998, 39.668   , 43.817   , 48.551   ]],

   [[37.292   , 28.454   , 23.414   , 23.018   , 21.83    ,
     19.472   , 28.364   , 35.492   , 28.786999, 36.23    ],
    [37.04    , 28.256   , 23.135   , 22.937   , 21.839   ,
     19.382   , 28.517   , 35.816   , 28.922   , 36.509   ]]],

largearray.shape =(2,2,10)

smallarray = array([[5,7],[9,3]])smallarray.shape =(2,2)

应该将3d数组的结果切成薄片,直到对应2d数组的值为止。结果应如下所示:

    array([[[36.914   , 38.795   , 37.733   , 36.68    , 35.411003],
   [37.121   , 38.723   , 37.706   , 36.653   , 35.491997, 33.638   ,
   36.697998]],
   [[37.292   , 28.454   , 23.414   , 23.018   , 21.83    , 19.472   ,
   28.364   , 35.492   , 28.786999],
   [37.04 , 28.256, 23.135]]])

最终的计算将在非常大的数组上进行,因此,如果计算尽可能便宜,那将是一个很好的选择。

希望您可以帮助我!

numpy 3d 2d slice numpy-slicing
1个回答
0
投票
如果将3D数组和2D数组分别转换为2D数组和1D数组,则计算会容易一些。

largearray = largearray.reshape(-1,largearray.shape[-1]) smallarray = smallarray.reshape(-1) ans = np.array([largearray[i,:smallarray[i]].tolist() for i in range(len(smallarray))]).reshape(2,2)

© www.soinside.com 2019 - 2024. All rights reserved.