rollit.mean: NumPy Rolling Mean without Pandas
The rollit.mean() function calculates the rolling mean (moving average) along a sliding window of a 1D NumPy array. By leveraging memory stride views, it runs directly in vectorized C loops at maximum speed without copying underlying elements.
Formula
For each window index, the simple moving average is defined as:
Where W is the window size and x represents the array elements within the sliding frame.
Parameters
arr (np.ndarray)
The input 1D numerical NumPy array containing floating-point or integer values. Must be a flat 1D array to maximize stride speed efficiency.
window (int)
The sliding window frame size. Must be a positive integer greater than zero and less than or equal to the array length.
min_periods (int | None, optional)
The minimum number of valid (non-NaN) observations required to return a value. If `None`, defaults to the window size, resulting in NaN if a single missing value enters the window.
Returns
np.ndarray
A flat 1D NumPy array containing the computed rolling averages. The output array has read-only flags enabled to prevent accidental write-corruption, and its length follows the standard window shrinkage: Output Length = len(arr) - window + 1.
Basic Example
import numpy as np
import rollit
# Generate 1D array of data (e.g. daily sensor readings)
data = np.array([10.0, 20.0, 15.0, 30.0, 25.0, 40.0])
# Compute 3-period moving average (zero-copy stride view)
ma = rollit.mean(data, window=3)
print("Input data:", data)
print("Rolling mean:", ma)
# Output: [15.0, 21.67, 23.33, 31.67]NaN Propagation & min_periods Example
If your data contains missing readings, use `min_periods` to prevent NaNs from propagating and ruining your downstream calculations.
import numpy as np import rollit # Array with NaN missing values arr = np.array([10.0, np.nan, 20.0, 30.0, 40.0]) # Default min_periods=None requires all elements in the window to be valid print(rollit.mean(arr, window=3)) # Output: [nan, nan, 30.0] # min_periods=2 computes mean if at least 2 non-NaN elements are present print(rollit.mean(arr, window=3, min_periods=2)) # Output: [15.0, 25.0, 30.0] # Window 1: [10.0, NaN, 20.0] -> 2 valid -> (10+20)/2 = 15.0 # Window 2: [NaN, 20.0, 30.0] -> 2 valid -> (20+30)/2 = 25.0 # Window 3: [20.0, 30.0, 40.0] -> 3 valid -> (20+30+40)/3 = 30.0