How to Calculate the Moving Average of a List in Python

71 views

How to Calculate the Moving Average of a List in Python

How to Calculate the Moving Average of a List in Python

I need to calculate the moving average of a list of numbers. How can I implement this?

solveurit24@gmail.com Changed status to publish February 16, 2025
0

The moving average can be calculated using a sliding window approach.

  1. Using a Sliding Window:
    • For each window of size n, compute the average.
  2. Code Example:

    def moving_average(numbers, window_size):
        averages = []
        for i in range(len(numbers) - window_size + 1):
            window = numbers[i:i+window_size]
            average = sum(window) / window_size
            averages.append(average)
        return averages
    
    my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    print(moving_average(my_list, 3))  # Output: [2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]
    


  3. Using the deque from collections:
    • Maintains a moving window efficiently.
  4. Alternative Code:

    from collections import deque
    
    def moving_average(numbers, window_size):
        window = deque(maxlen=window_size)
        averages = []
        for number in numbers:
            window.append(number)
            if len(window) == window_size:
                average = sum(window) / window_size
                averages.append(average)
        return averages
    
    my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    print(moving_average(my_list, 3))  # Output: [2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]
    


  5. Explanation:
    • The deque approach efficiently maintains the current window of numbers.
    • Both methods provide the same result but with different approaches to window management.
solveurit24@gmail.com Changed status to publish February 16, 2025
0