Moving non-overlapping window in Numpy

故事扮演 提交于 2019-12-12 04:57:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!