Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
505 views
in Technique[技术] by (71.8m points)

python - Numpy Two-Dimensional Moving Average

I have a 2d numpy array. I want to take the average value of the n nearest entries to each entry, just like taking a sliding average over a one-dimensional array. What is the cleanest way to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is a similar concept to applying a filter to an image.

Fortunately, scipy.ndimage.filters has a bunch of functions to do that. The one you're after is scipy.ndimage.uniform_filter.

Can be used like this:

a
=> 
array([[  0.,   1.,   2.,   3.,   4.],
       [  5.,   6.,   7.,   8.,   9.],
       [ 10.,  11.,  12.,  13.,  14.],
       [ 15.,  16.,  17.,  18.,  19.],
       [ 20.,  21.,  22.,  23.,  24.]])

uniform_filter(a, size=3, mode='constant')
=> 
array([[  1.33333333,   2.33333333,   3.        ,   3.66666667,          2.66666667],
       [  3.66666667,   6.        ,   7.        ,   8.        ,          5.66666667],
       [  7.        ,  11.        ,  12.        ,  13.        ,          9.        ],
       [ 10.33333333,  16.        ,  17.        ,  18.        ,         12.33333333],
       [  8.        ,  12.33333333,  13.        ,  13.66666667,          9.33333333]])

If you want a 5x5 filter, use size=5. The mode option controls how the edges are treated. You didn't specify how you want to handle the edges. In this example, the "constant" mode means it treats each item outside the bounds of the array as a constant value of 0 (0 is the default, which can be overridden).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...