Search code examples
listmathjupyter-notebooktime-series

How to perform mathematical operations within a list?


I have a list where

YEAR    MONTH
1960    5
1961    7
1961    8
1961    11
1962    5
1963    6
1964    
1965    7
1966    7
1966    7
1966    10
1967    4
1967    8
1968    
1969    
1970    8
1971    6
1971    9
1971    10
1972    7
1973    6
1973    9
1974    10
1974    10
1975    10
1976    
1977    
1978    9
1979    11
1980    7
1980    7
1980    8
1981    
1982    10
1982    12
1983    
1984    7
1985    9
1986    
1987    
1988    9
1988    10
1989    7
1989    10
1990    
1991    7
1992    
1993    6
1993    7
1993    9
1993    9
1994    
1995    7
1996    8
1996    9
1997    5
1998    8
1998    9
1998    10
1999    8
1999    9
2000    9
2001    
2002    1
2003    5
2003    7
2003    8
2003    9
2003    10
2004    
2005    11
2006    7
2006    10
2007    9
2007    11
2007    11
2008    5
2009    5
2009    7
2009    9
2009    9
2010    10
2011    5
2011    9
2011    9
2012    8
2013    7
2014    9
2015    7
2016    
2017    8
2018    10
2019    11
2020    

I want to perform a running smoothing timeseries to generate another list using the formula:

((A-E)+3*(B+D)+4*C)/12

Where the last value is until z. I cannot find samples where mathematical operations is found within the list. Most references and samples are between two lists. I am using Jupyter Notebook.


Solution

  • You can use a sliding window approach. This means that you will take a window of a certain size, and slide it over the data, performing the calculation at each step.

    If you want to use a window size of 5, you can start by performing the calculation for the first 5 elements of the list: (A-E)+3*(B+D)+4C. Then you can move the window one element to the right, and recalculate the smoothed value using the next 5 elements: (B-F)+3(C+E)+4*D. You can continue this process until you reach the end of the list.

        def running_smooth(data, window_size):
          smoothed_data = []
          for i in range(len(data) - window_size + 1):
            window = data[i:i+window_size]
            #calculation here
            value = (window[0]-window[4]) + 3*(window[1]+window[3]) + 4*window[2]
            smoothed_data.append(value)
          return smoothed_data