Advertisement
Guest User

Untitled

a guest
Dec 5th, 2016
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.17 KB | None | 0 0
  1.     def moving_average(self, sampling_period,
  2.                        window_size=None,
  3.                        start=None, end=None,
  4.                        placement='center',
  5.                        pandas=False):
  6.         """Averaging over regular intervals
  7.  
  8.        """
  9.         start, end, mask = self._check_boundaries(start, end)
  10.  
  11.         # default to sampling_period if not given
  12.         if window_size is None:
  13.             window_size = sampling_period
  14.  
  15.         sampling_period = \
  16.             self._check_regularization(start, end, sampling_period)
  17.  
  18.         # convert to datetime if the times are datetimes
  19.         half_window = float(window_size) / 2
  20.         full_window = float(window_size)
  21.         if isinstance(start, datetime.datetime):
  22.             half_window = datetime.timedelta(seconds=half_window)
  23.             full_window = datetime.timedelta(seconds=full_window)
  24.  
  25.         result = []
  26.         current_time = start
  27.         while current_time <= end:
  28.  
  29.             if placement == 'center':
  30.                 window_start = current_time - half_window
  31.                 window_end = current_time + half_window
  32.             elif placement == 'left':
  33.                 window_start = current_time
  34.                 window_end = current_time + full_window
  35.             elif placement == 'right':
  36.                 window_start = current_time - full_window
  37.                 window_end = current_time
  38.             else:
  39.                 msg = 'unknown placement "{}"'.format(placement)
  40.                 raise ValueError(msg)
  41.  
  42.             # calculate mean over window and add (t, v) tuple to list
  43.             mean = self.mean(window_start, window_end)
  44.             result.append((current_time, mean))
  45.  
  46.             current_time += sampling_period
  47.  
  48.         # convert to pandas Series if pandas=True
  49.         if pandas:
  50.  
  51.             try:
  52.                 import pandas as pd
  53.             except ImportError:
  54.                 msg = "can't have pandas=True if pandas is not installed"
  55.                 raise ImportError(msg)
  56.  
  57.             result = pd.Series(
  58.                 [v for t, v in result],
  59.                 index=[t for t, v in result],
  60.             )
  61.  
  62.         return result
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement