0

I am trying to calculate the moving average on my data. I am facing the error as I mentioned in the title.

Here is my code:

def moving_average(input, window_size):
    result = []
    moving_sum = sum(input[:window_size])
    result.append(moving_sum/window_size)
    for i in range(len(input) - window_size):
        moving_sum += (input[i + window_size]-input[i])
        result.append(moving_sum/window_size)
        
    return result
result = moving_average(df['PR'], 30)
print(result)

I am trying to calculate a 30-day moving average. Here is the error I got:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
~\AppData\Roaming\Python\Python39\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   3801             try:
-> 3802                 return self._engine.get_loc(casted_key)
   3803             except KeyError as err:

~\AppData\Roaming\Python\Python39\site-packages\pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

~\AppData\Roaming\Python\Python39\site-packages\pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

KeyError: 0

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_14940\870804258.py in <module>
----> 1 result = moving_average(df['PR'], 30)
      2 print(result)

~\AppData\Local\Temp\ipykernel_14940\3000037760.py in moving_average(input, window_size)
      4     result.append(moving_sum/window_size)
      5     for i in range(len(input) - window_size):
----> 6         moving_sum += (input[i + window_size]-input[i])
      7         result.append(moving_sum/window_size)
      8 

~\AppData\Roaming\Python\Python39\site-packages\pandas\core\series.py in __getitem__(self, key)
    979 
    980         elif key_is_scalar:
--> 981             return self._get_value(key)
    982 
    983         if is_hashable(key):

~\AppData\Roaming\Python\Python39\site-packages\pandas\core\series.py in _get_value(self, label, takeable)
   1087 
   1088         # Similar to Index.get_value, but we do not fall back to positional
-> 1089         loc = self.index.get_loc(label)
   1090         return self.index._get_values_for_loc(self, loc, label)
   1091 

~\AppData\Roaming\Python\Python39\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   3802                 return self._engine.get_loc(casted_key)
   3803             except KeyError as err:
-> 3804                 raise KeyError(key) from err
   3805             except TypeError:
   3806                 # If we have a listlike key, _check_indexing_error will raise

KeyError: 0
Karthik Bhandary
  • 1,305
  • 2
  • 7
  • 16
  • You can use `rolling` function of pandas. For example, if the data is monthly, use `df.rolling(30).mean()`. Details can be found here: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.rolling.html – EMT Jun 15 '23 at 08:21

0 Answers0