从给定的索引堆栈切片numpy数组

时间:2018-01-28 06:54:16

标签: python numpy slice

我正在努力在numpy向量上执行以下操作。

我想从previous_n结束vector处的indices个样本。

就像我想要np.take切片previous_n样本一样。

示例:

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])

结果

array([[ 3,  4,  5],
       [ 5,  6,  7],
       [10, 11, 12]])

1 个答案:

答案 0 :(得分:0)

好的,这似乎做了我想要的。找到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]])
相关问题