Sliding average of NumPy arrays in Python
The sliding average is often used to study time series data by calculating the average of data at a specific time interval. It is used to eliminate some short-term fluctuations and study data trends. When studying stock price trends, the simple sliding average is used a lot.
A weighted moving average places more emphasis on the most recent data than on older data.
The following chart will give a better understanding of the sliding average.
In this tutorial, we will discuss how to implement a sliding average for a numpy array in Python.
Use numpy.convolve
the method to calculate the sliding mean of a NumPy array.
convolve()
The function is used for signal processing and can return the linear convolution of two arrays. What each step does is take the inner product between an array and the current window and take their sum.
The following code implements this functionality in a user-defined function.
import numpy as np
def moving_average(x, w):
return np.convolve(x, np.ones(w), "valid") / w
data = np.array([10, 5, 8, 9, 15, 22, 26, 11, 15, 16, 18, 7])
print(moving_average(data, 4))
Output:
[ 8. 9.25 13.5 18. 18.5 18.5 17. 15. 14. ]
Use scipy.convolve
the method to calculate the sliding mean of a NumPy array.
We can also use the numpy function in the same way scipy.convolve()
. Let's say it is a bit faster. Another way to calculate the sliding average using the numpy module is to use cumsum()
the numpy function. It calculates the cumulative sum of an array. This is a very simple non-weighted method to calculate a sliding average.
The following code uses this function to return a sliding average.
def moving_average(a, n):
ret = np.cumsum(a, dtype=float)
ret[n:] = ret[n:] - ret[:-n]
return ret[n - 1 :] / n
data = np.array([10, 5, 8, 9, 15, 22, 26, 11, 15, 16, 18, 7])
print(moving_average(data, 4))
Output:
[ 8. 9.25 13.5 18. 18.5 18.5 17. 15. 14. ]
Use bottleneck
the module to calculate the sliding average
bottleneck
The module is a compilation of fast numpy methods. The module has move_mean()
a function that returns a sliding average of some data.
For example,
import bottleneck as bn
import numpy as np
def rollavg_bottlneck(a, n):
return bn.move_mean(a, window=n, min_count=None)
data = np.array([10, 5, 8, 9, 15, 22, 26, 11, 15, 16, 18, 7])
print(rollavg_bottlneck(data, 4))
Output:
[ nan nan nan 8. 9.25 13.5 18. 18.5 18.5 17. 15. 14. ]
Since the time window interval is 4, there are three nan values at the beginning because the sliding average cannot be calculated for them.
Use pandas
the module to calculate the sliding average
Time series data is primarily pandas
associated with DataFrames. Hence, this library is perfect for performing different computations on such data.
We can use the rolling()
and mean()
functions to calculate the moving average of time series data as shown below.
import pandas as pd
import numpy as np
data = np.array([10, 5, 8, 9, 15, 22, 26, 11, 15, 16, 18, 7])
d = pd.Series(data)
print(d.rolling(4).mean())
Output:
0 NaN
1 NaN
2 NaN
3 8.00
4 9.25
5 13.50
6 18.00
7 18.50
8 18.50
9 17.00
10 15.00
11 14.00
dtype: float64
We first convert the numpy array to a time series object, then use rolling()
the function to perform calculations on the rolling window and mean()
the function to calculate the sliding average.
This is also because the time window interval is 4, so there are three nan values at the beginning because the sliding average cannot be calculated for them.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Calculating Mahalanobis distance in Python
Publish Date:2025/05/05 Views:185 Category:Python
-
This tutorial will show you how to find the Mahalanobis distance between two NumPy arrays in Python. Use the function scipy.spatial.distance in the Python library cdist() to calculate the Mahalanobis distance The Mahalanobis distance is a m
Implementing the ReLU function in Python
Publish Date:2025/05/05 Views:177 Category:Python
-
This tutorial will discuss the Relu function and how to implement it in Python. ReLU function Relu Functions are the foundation of machine learning and are essential when using deep learning. ReLU The term is Rectified Linear Unit an acrony
Killing a Python process
Publish Date:2025/05/05 Views:152 Category:Python
-
When programming in Python, sometimes our program gets stuck in an infinite loop. In this case, we need to terminate the program manually. This article will discuss different ways to kill a Python process. Killing a Python process using a k
Get file extension in Python
Publish Date:2025/05/05 Views:63 Category:Python
-
This tutorial shows how to get the file extension from a file name in Python. os.path Extract extension from file using module in Python The Python module os.path pre-makes useful utility functions for manipulating operating system file pat
Read the first line of a file in Python
Publish Date:2025/05/05 Views:192 Category:Python
-
In Python, we have built-in functions to handle different file operations. A text file contains a sequence of strings where each line \n is terminated by a newline character. In this tutorial, we will learn how to read the first line of a t
Reading binary files in Python
Publish Date:2025/05/05 Views:119 Category:Python
-
The program or internal processor interprets the binary file. It contains bytes as content. When we read a binary file, an bytes object of type is returned. open() Read a binary file using the function in Python In Python, we have open() th
Writing bytes to a file in Python
Publish Date:2025/05/05 Views:193 Category:Python
-
In this tutorial, we will look at how to write bytes to a binary file in Python. Binary files contain strings of type bytes. When we read a binary file, an object of type bytes is returned. In Python, bytes are represented by hexadecimal nu
Python get file name without extension from path
Publish Date:2025/05/05 Views:81 Category:Python
-
This tutorial will demonstrate various ways to get the file name without extension from a file path in Python. Suppose our goal is to get the file name from a list of file paths that are in the form of strings, such as from the path Desktop
Calculate the time difference between two time strings in Python
Publish Date:2025/05/05 Views:182 Category:Python
-
Sometimes we have to deal with date and time related problems in programming. In Python, date and time are not data types themselves. Despite this, Python provides a large number of functions and libraries to help deal with such problems. O