0

Suppose I have 2-dimensional numpy array e.g.:

arr = np.arange(15).reshape(5,3)

array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11],
       [12, 13, 14]])

I would like to efficiently slice different columns for different rows. For example, I want to have 0:2 for the 0th row, 1:3 for the 1st row, 0:2 for the 2nd row, 1:3 for the 3rd row and 1:3 for the 4th row. I can do this inefficiently with a loop as:

min_index = (0,1,0,1,1)
max_index = (2,3,2,3,3)

newarr = []
count = 0
for min_,max_ in zip(min_index,max_index):
    newarr.append(arr[count,min_:max_])
    count += 1
np.array(newarr)

array([[ 0,  1],
       [ 4,  5],
       [ 6,  7],
       [10, 11],
       [13, 14]])

This works but it is not efficient. Is there way to efficiently do this slicing? I tried

arr[range(5),(0,1,0,1,0):(1,2,1,2,1)]

but this did not work.

FairyOnIce
  • 2,526
  • 7
  • 27
  • 48
  • See this question. https://stackoverflow.com/questions/47982894/selecting-random-windows-from-multidimensional-numpy-array-rows/47982961#47982961 – Psidom Jan 03 '18 at 03:14
  • Is the last entry of min_index and max_index a typo? Are you looking for truly arbitrary indices or this specific pattern? – Mad Physicist Jan 03 '18 at 03:25
  • @Psidom. Not 100% dupe but contains the generalized answer. What to do? – Mad Physicist Jan 03 '18 at 03:38
  • @MadPhysicist Hmm, if the window size is constant among pairs of min max index, then it turns into the same question. But it could be a different question if the answer from the linked question doesn't satisfy OP's expectation; The chance is slim though. Maybe just let OP decides. – Psidom Jan 03 '18 at 03:47
  • @MadPhysicist The last indices are not typo. The indices are arbitrary. But yes, window size is constant. – FairyOnIce Jan 03 '18 at 04:06

0 Answers0