[英]How to slice array into sequences arrays?
我有一個用於特征和標簽的時間序列數組,例如
x=[1,2,3,4,5,6......100]
y=[0.5,0.8,0.9,0.5,0.9,0.8,....,0.9]
我想使它成為動態子數組,如i = 3然后
x=[1,2,3],[2,3,4],[3,4,5],...
y=[0.5,0.8,0.9],[0.8,0.9,0.5],[0.9,0.5,0.9],...
所以我知道t[1:i]
將第一個元素賦予第i個元素,但是如何連續進行。 任何幫助表示贊賞。
您想要的是一種從序列計算滑動窗口的方法。
從滾動或滑動窗口迭代器修改解決方案? 通過@Daniel DiPaolo
from itertools import islice
def window(seq, n=2):
"Returns a sliding window (of width n) over data from the iterable"
" s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ... "
it = iter(seq)
result = list(islice(it, n))
if len(result) == n:
yield result
for elem in it:
result = result[1:] + [elem]
yield result
from functools import partial
def group_slice(*args, winsize):
yield from zip(*map(partial(window, n=winsize), args))
def group_slice(*args, winsize):
# Slightly clearer version of the above
partial_func = partial(window, n=winsize)
yield from zip(*(partial_func(s) for s in args))
group_slice
在做什么
創建一個部分功能進行的window
與窗口大小的給定值。
將此部分“修改的” window
函數應用於每個序列,以獲取生成器的集合。
然后從每個生成器產生每個切片。
你這樣用
x = [1,2,3,4,5,6]
y = [0.5,0.8,0.9,0.5,0.9,0.8]
for x_slice, y_slice in group_slice(x, y, winsize=3):
print(x_slice)
print(y_slice)
將輸出
[1, 2, 3]
[0.5, 0.8, 0.9]
[2, 3, 4]
[0.8, 0.9, 0.5]
[3, 4, 5]
[0.9, 0.5, 0.9]
[4, 5, 6]
[0.5, 0.9, 0.8]
或者如果您只想要單個組的列表
x_slices = list(window(x, n=3))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.