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.