Running Mean in Python with NumPy
Calculating the running mean, also known as the moving average, of a 1D array is a common task in data analysis. NumPy provides a powerful tool called np.convolve for performing convolution operations, including the running mean.
Definition and Implementation:
The running mean involves sliding a window along the input array and computing the mean of the values within the window at each step. In NumPy, this is achieved as follows:
import numpy as np array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] window_size = 3 result = np.convolve(array, np.ones(window_size) / window_size, mode='valid')
Explanation:
Edge Handling:
The mode argument in np.convolve controls how the edges of the array are handled during convolution. The available modes are 'full', 'same', and 'valid':
The 'valid' mode is typically used for the running mean, as it provides a result that does not include the windowed sections of the beginning and end of the array.
Example:
In the example above, the result will be:
[4. 5. 6. 7. 8. 9.]
This represents the running mean of the input array with a window size of 3.
The above is the detailed content of How to Calculate a Running Mean (Moving Average) in Python Using NumPy?. For more information, please follow other related articles on the PHP Chinese website!