将数组拆分为大小相等的窗口 [英] Split array into equal sized windows

查看:72
本文介绍了将数组拆分为大小相等的窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将长度为40的 numpy.array 拆分为较小的,相等大小的 numpy.array s,其中较小数组的数目由用户指定。允许在较小的数组之间存在一些重叠,因为在给定较小数组的某种重叠形式的情况下,可能会发生全长只能被分割整除的情况。

I am trying to split an numpy.array of length 40 into smaller, equal-sized numpy.arrays, in which the number of the smaller arrays is given by the user. It is allowed to have some overlap between the smaller arrays, as situations can occur where the full length is only divisible by the splits given some form of overlap of the smaller arrays.

如果我有一个数组 np.array([range(40)])
必须将其拆分为37个子数组,子数组列表应如下所示:

If I had an array np.array([range(40)]) And I had to split it into 37 sub arrays, the list of subarrays should be like this:

[1, 2, 3], [3, 4, 5], [5, 6, 7], ... [38, 39, 40]

我尝试使用 numpy.split ,但这仅在长度可以被大小整除时有效,而 numpy.array_split 会产生不均匀的大小。

I tried using numpy.split but this only works when the length is divisible by the size, and numpy.array_split generates uneven sizes.

使用 numpy.split

>> import numpy as np
>>> a = np.random.randint(6,size=(40))
>>> b = np.split(a,37)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/site-packages/numpy/lib/shape_base.py", line 508, in split
    'array split does not result in an equal division')
ValueError: array split does not result in an equal division

并且 numpy.array_split

>>> a = np.random.randint(5,size=(40))
>>> b = np.array_split(a,37)
>>> print len(b)
37
>>> print b[0].shape
(2,)
>>> print b[3].shape
(1,)
>>> print b[5].shape
(1,)
>>> print b[6].shape
(1,)
>>> print b[30].shape
(1,)
>>> 

numpy.array_split 不等分

任何解决方案?

推荐答案

您要描述的内容称为(滑动)窗口,而不是拆分窗口。

What you're describing is called a (sliding) window, not a split.

查看此答案: https://stackoverflow.com/a/15722507/7802200

您要使用的是 window_stack 函数在那里开发,宽度为 len(a)的宽度-n_splits + 1

What you want is to use the window_stack function developed there with a width of len(a) - n_splits + 1.

这篇关于将数组拆分为大小相等的窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆