![](/img/trans.png)
[英]Taking multiple slices of numpy 1d array from given indices, copying result into 2d array
[英]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.