簡體   English   中英

從給定索引堆疊numpy數組的切片

[英]Stack slices of numpy array from given indices

我正在努力對numpy向量執行以下操作。

我想從indices處的vector精加工中獲取previous_n樣本。

就像我要對previous_n樣本進行切片時執行np.take一樣。

例:

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

好的,這似乎可以滿足我的要求。 這里找到

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM