| 1. |
How will you implement the moving average for the 1D array in NumPy? |
|
Answer» We can make use of the convolve() method. Here, it leverages the way discrete convolution is computed and uses it to find the rolling mean (moving average). Here, the sequence of ones of length equal to the length of the sliding window is convolved with the array. We first define a calculate_moving_average function which performs the convolution of an array with the sequence of ones of sliding window length w. The mode of the convolve method will be ‘valid’ to generate the points only where the overlapping of the sequence is complete. import numpy as npdef calculate_moving_average(arr, w): return np.convolve(arr, np.ones(w),'valid')/w The above-defined function can be then used for finding the moving average as shown in the examples below: arr1 = np.array([4,5,8,9,3,2,4,2,0,2])print("Moving average of window length 2: ") av1 = calculate_moving_average(arr1, 2) print(av1) print("Moving average of window length 4: ") av2 = calculate_moving_average(arr1, 4) print(av2) Output: Moving average of window length 2:[4.5 6.5 8.5 6. 2.5 3. 3. 1. 1. ] Moving average of window length 4: [6.5 6.25 5.5 4.5 2.75 2. 2. ] |
|