rougier/numpy-100

An alternative solution for Q.75

iamyifan opened this issue · 3 comments

  1. How to compute averages using a sliding window over an array? (★★★)
    hint: np.cumsum

# Author: Jaime Fernández del Río

def moving_average(a, n=3) :
ret = np.cumsum(a, dtype=float)
ret[n:] = ret[n:] - ret[:-n]
return ret[n - 1:] / n
Z = np.arange(20)
print(moving_average(Z, n=3))

NumPy 1.20.0. provides a function numpy.lib.stride_tricks.sliding_window_view, which can create a sliding window view into the array with the given window shape. Doc

Thus, an alternative solution will be:

from numpy.lib.stride_tricks import sliding_window_view

Z = np.arange(20)
print(sliding_window_view(Z, window_shape=3).mean(axis=-1))

At last! Can you make a PR (just adding the new version specifying this is for numy 1.20)?

At last! Can you make a PR (just adding the new version specifying this is for numy 1.20)?

Sure. I'll make a PR this weekend.
Again, thanks for your numpy-100 practice, it really helps me a lot.

Make sure to update the .ktx files, not the .md ones