I want to slice an array without knowing its dimensions. Indexes(start and end are given in list format. How to do this? Thank you.
Slice 1d array
import numpy as np
a = np.array([1, 2, 3, 4, 5, 6])
# idx: [2, 5)
print(a[2:5])
# [3, 4, 5]
Slice 2d array
import numpy as np
a = np.array([
[1, 2, 3],
[2, 3, 2],
[4, 5, 2]
])
start = [0, 1]
end = [1, 2]
print(a[start[0]:end[0], start[1]:end[1]])
Slice N-d array?
a = np.array([
[[1, 0, 2],
[2, 1, 0],
[5, 6, 3]],
[[2, 1, 3],
[3, 2, 1],
[1, 4, 6]]
])
start = [0, 0, 1]
end = [1, 1, 2]
result = a[start[0]:end[0], start[1]:end[1], start[2]:end[2]] # key point: how to adapt this?
print(result)
len(a.shape)to find out the number of dimensions and then you can loop through all of the dimensions to find out the number of values in the dimension.