问题
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!
回答1:
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?
来源:https://stackoverflow.com/questions/26939931/moving-non-overlapping-window-in-numpy