Python
NumPy
SciPy
Rolling Average
Moving Average

How to calculate a rolling (moving) average with NumPy and SciPy

Codemia Knowledge Hub ·

The usual NumPy ways to compute a rolling average are convolution with a flat kernel (np.convolve) and differences of cumulative sums (np.cumsum). SciPy's uniform_filter1d does the same smoothing with explicit control over what happens at the edges. Pick based on speed, edge handling, and whether the output must match the input length.

Simple moving average with np.convolve

A simple moving average is convolution with a flat kernel whose values sum to 1.

python
1import numpy as np
2
3x = np.array([1, 2, 3, 4, 5], dtype=float)
4window = 3
5kernel = np.ones(window) / window
6
7avg = np.convolve(x, kernel, mode="valid")
8print(avg)

With mode="valid", only positions where the full window fits are returned, so the output is shorter than the input. This is the most concise option for a one-dimensional array when a shorter result is acceptable.

Sliding sums with np.cumsum

The cumulative-sum approach is also efficient on large arrays.

python
1import numpy as np
2
3x = np.array([1, 2, 3, 4, 5], dtype=float)
4window = 3
5cumsum = np.cumsum(np.insert(x, 0, 0.0))
6avg = (cumsum[window:] - cumsum[:-window]) / window
7
8print(avg)

Once you have cumulative sums, the sum of any fixed-width window is a single subtraction, so no window sum is recomputed from scratch. It also makes the mechanics of the rolling average explicit instead of hiding them in a library call.

Keeping the output length with mode="same"

If you want one result per input element, you have to decide what happens at the edges where a full centered window does not fit. The quick option is mode="same":

python
1import numpy as np
2
3x = np.array([1, 2, 3, 4, 5], dtype=float)
4kernel = np.ones(3) / 3
5avg = np.convolve(x, kernel, mode="same")
6
7print(avg)

The output length matches the input, but the boundary values depend on how convolution pads the missing values, which may not be what you want. The real question is what should happen at the edges.

Explicit edge handling with SciPy

SciPy's filters let you choose the boundary rule directly:

python
1import numpy as np
2from scipy.ndimage import uniform_filter1d
3
4x = np.array([1, 2, 3, 4, 5], dtype=float)
5avg = uniform_filter1d(x, size=3, mode="nearest")
6
7print(avg)

The mode argument controls which values are assumed beyond the boundaries. nearest extends the edge value outward; other modes behave differently. This is clearer than working out what a particular convolution padding does to the first and last few elements.

Choosing the window size

The window size sets how aggressively the series is smoothed:

  • a small window preserves short-term variation,
  • a large window emphasizes long-term trends,
  • a centered window behaves differently from a trailing window used in time-series reporting.

For dashboards or finance-style reporting, make sure the window definition matches the business meaning. A correct average over the wrong window is still the wrong answer.

Handling NaN values

Pure NumPy approaches propagate NaN values unless you handle them. If the data can have missing entries, decide whether to ignore them, fill them, or let them invalidate each window. That choice changes the implementation, and no single rule is correct for every case.

Mistakes to avoid

  • Using mode="same" without understanding the implied edge behavior.
  • Expecting a centered moving average when the code computes a trailing one.
  • Forgetting that valid mode shortens the output array.
  • Picking a window size for looks rather than for what the signal means.
  • Ignoring NaN handling when the input is incomplete.

Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No course covers this one yet

Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.

Build my course
ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design