Home > AI > Language > Python >

slice array without knowing its dimensions

Example 1: 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]

Example 2: 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]])

Example 3: without knowing its dimensions

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]

result1 = a[start[0]:end[0], start[1]:end[1], start[2]:end[2]] # key point: how to adapt this?

result2 = a[tuple(slice(*indexes) for indexes in zip(start, end))] 

assert np.all(result2 == result2) 

Leave a Reply