1

I got a question regarding slicing of a 3d array with use of a 2d array. largearray is the 3d array which I want to slice with values from the 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)

The result should from the 3d array should be sliced up until the value from the corresponding 2d array. The result should look like this:

    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]]])

The eventual calculations will be on very large arrays, thus it would be great if the computation is as computationally cheap as possible.

Hope you can help me with this!

1 Answers1

0

The calculation's a bit easier if the 3D array and 2D arrays are converted to a 2D array and 1D array respectively.

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)
Mercury
  • 3,417
  • 1
  • 10
  • 35
  • Thanks for the quick response! Would this still work if you go from a 4d array to a 3d array? – Rens Vermeltfoort May 28 '20 at 13:28
  • If it's a similar scenario, then yes. For example, if your large array was 5x2x2x10 and small array was 5x2x2, you could simply squish it down to 20x10 and 20 in the same way. – Mercury May 28 '20 at 15:51