Home > Backend Development > Python Tutorial > How to Efficiently Calculate a Running Mean in Python using NumPy or SciPy?

How to Efficiently Calculate a Running Mean in Python using NumPy or SciPy?

Patricia Arquette
Release: 2024-11-30 07:05:12
Original
805 people have browsed it

How to Efficiently Calculate a Running Mean in Python using NumPy or SciPy?

Calculating Running Mean with NumPy or SciPy

When performing data analysis, calculating the running mean (also known as moving average) for a 1D array is a common operation. Python's SciPy and NumPy libraries provide several functions for this purpose.

NumPy Solution

NumPy's np.convolve function can be leveraged for running mean calculations. It computes a convolution operation on the input array, where the kernel is a uniform distribution representing the desired window size.

np.convolve(x, np.ones(N)/N, mode='valid')
Copy after login

where:

  • x is the input 1D array
  • N is the window size
  • mode='valid' handles edges as expected (output length equals input length minus window size)

Understanding the Computation

The running mean is essentially a convolution operation, where the window coefficients are all set to 1/N. Therefore, using NumPy's convolution function is computationally efficient.

Edge Handling Modes

np.convolve offers three edge handling modes:

  • full: Extends input array by padding with zeros
  • same: Outputs an array the same length as the input by zero-padding both ends
  • valid: Ignores edges and outputs an array of length (len(input) - window_size 1)

The mode is set to valid by default, as it typically aligns with the intuitive behavior of running mean calculations, but other modes can be used depending on specific requirements.

The above is the detailed content of How to Efficiently Calculate a Running Mean in Python using NumPy or SciPy?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template