fmagno
fmagno

Reputation: 1548

Slicing below the limits of a numpy array

Let's say a = np.array([0,1,2,3,4,5])

Is there a mechanism of slicing below the lower boundary? E.g: a[-2:3] -> [0,1,2]

x x {x x 0 1 2} 3 4 5 x x x x
{x x 0 1 2}
{0 1 2}

PS: I know that negative indexes are relative to the end of the array

Upvotes: 1

Views: 45

Answers (2)

pandrey
pandrey

Reputation: 364

Why not simply use max to handle auto-generated negative values?

a = np.array([0,1,2,3,4,5])
x = -2
a[max(0, x), 3]  # this is equivalent to a[:3]

Upvotes: 1

kabanus
kabanus

Reputation: 25895

No, there is no such mechanism. One option is this wrapper:

def my_slicer(arr,i,j):
    if i < 0: i = 0
    if j >=arr.shape[0]: j = arr.shape[0]-1
    return arr[i:j]

Of course, this assumes a single dimension.

Upvotes: 2

Related Questions