简体   繁体   中英

Moving non-overlapping window in Numpy

What's the best way to move a window over a numpy array so that each individual block does not overlap with the previous one and there is a 1 element gap between the blocks? I guess I should use np.hstack, but I can't figure out the slicing pattern.

Basically what I am looking for is this:

a = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
result = np.array([[0, 1, 2, 3],
                   [5, 6, 7, 8])

Thanks!

What you want to to achieve in your short example can be done by reshaping the array, then removing the last column to create a "gap".

import numpy as np

a = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

# get length of flat array
a_length, =  a.shape

# reshape array 
#(column by row must respect number of elements)
b = a.reshape(( 2, a_length/2 ))

# assign array except last column to a variable
result = b[:,:-1]
print result

Would that be general enough as to answer your question?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM