[Numpy-discussion] view 1d array as overlapping segments?

eat e.antero.tammi at gmail.com
Mon Mar 7 10:31:37 EST 2011


Hi,

On Mon, Mar 7, 2011 at 5:01 PM, Neal Becker <ndbecker2 at gmail.com> wrote:

> reshape can view a 1d array as non-overlapping segments.
>
> Is there a convenient way to view a 1d array as a 2d array of overlapping
> segments?
>
> nonoverlapping:
> l: segment length
> k: overlap
> u is the 1d array
> v is a 2d array
>
> v[i] = u[l*i:(l+1)*i]
>
> overlapping:
> v[i] = u[l*i:(l+1)*i+k]
>
In case actually  v[i]= u[i* l: (i+ 1)* l+ k], then this may be useful
from numpy.lib.stride_tricks import as_strided as ast

def os(a, l, k= 0):
    shape, strides= (a.shape[0]- l+ 1, l+ k), a.strides* 2
    return ast(a, shape= shape, strides= strides)

if __name__ == '__main__':
    import numpy as np
    a= np.arange(7, dtype= np.int8)
    print os(a, 3)
    # [[0 1 2]
    #  [1 2 3]
    #  [2 3 4]
    #  [3 4 5]
    #  [4 5 6]]
    print os(a, 3, 2)
    # [[ 0  1  2  3  4]
    #  [ 1  2  3  4  5]
    #  [ 2  3  4  5  6]
    #  [ 3  4  5  6  0]  # last item garbage
    #  [ 4  5  6  0 34]] # 2 last items garbage

My two cents,
eat

> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20110307/29ffcf39/attachment.html>


More information about the NumPy-Discussion mailing list