1

I'm struggling to perform the below operation on a numpy vector.

I want to take previous_n samples from vector finishing at indices.

It's like I want to perform a np.take with slicing of the previous_n samples.

Example:

import numpy as np

vector = np.array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14])

# number of previous samples
previous_n = 3

indices = np.array([ 5,  7, 12])

result

array([[ 3,  4,  5],
       [ 5,  6,  7],
       [10, 11, 12]])
James Schinner
  • 1,549
  • 18
  • 28

1 Answers1

0

Ok, this seems to do what I want. Found here

def stack_slices(arr, previous_n, indices):
    all_idx = indices[:, None] + np.arange(previous_n) - (previous_n - 1)
    return arr[all_idx]

>>> stack_slices(vector, 3, indices)
array([[ 3,  4,  5],
       [ 5,  6,  7],
       [10, 11, 12]])
James Schinner
  • 1,549
  • 18
  • 28