-1

If i have a numpy array:

arr = np.array([1,2,3,4,5,6,7,8,9,10])
x = 3 # index
n = 5
m = 2

Is there a way to get an output like this?

output: np.array([1,2,3,4,5,6])

We start at 4 which is index x=3. The output consists of n=5 elements before said index, but does not wrap around (doesn't go beyond the 1 in this case). And also consists of m=2 elements after said index.

Thank you.

Knovolt
  • 95
  • 8

1 Answers1

1

You can use this:

import numpy as np
arr = np.array([1,2,3,4,5,6,7,8,9,10])
x = 3
n = 5
m = 2
arr[max(0, x-n):x+m+1]
# array([1, 2, 3, 4, 5, 6])
Matthias Fripp
  • 17,670
  • 5
  • 28
  • 45