如何将数组切成序列数组?

时间:2018-10-18 04:43:11

标签: python arrays python-3.x

我有一个用于特征和标签的时间序列数组

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个元素,但是如何连续进行。 任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:3)

您想要的是一种从序列中计算滑动窗口的方法。

通过@Daniel DiPaolo从Rolling or sliding window iterator?修改解决方案

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在做什么

  1. 使用给定值window创建一个局部函数 窗口大小。

  2. 将此部分“修改的” window函数应用于每个序列,以 获取发电机的集合。

  3. 然后从每个生成器生成每个切片。

您像这样使用它

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