我有一个名为moving_average的python Pandas 系列。

moving_average = df['score'].rolling(window=period).mean()

我想检索moving_average系列的最后一个元素。这就是我所做的。
moving_average = df['score'].rolling(window=period).mean()[-1]

不幸的是,我收到以下错误。
  File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\series.py", line 601, in __getitem__
    result = self.index.get_value(self, key)
  File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexes\base.py", line 2477, in get_value
    tz=getattr(series.dtype, 'tz', None))
  File "pandas\_libs\index.pyx", line 98, in pandas._libs.index.IndexEngine.get_value
  File "pandas\_libs\index.pyx", line 106, in pandas._libs.index.IndexEngine.get_value
  File "pandas\_libs\index.pyx", line 154, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\hashtable_class_helper.pxi", line 759, in pandas._libs.hashtable.Int64HashTable.get_item
  File "pandas\_libs\hashtable_class_helper.pxi", line 765, in pandas._libs.hashtable.Int64HashTable.get_item
KeyError: -1

我正在使用python v3.6

最佳答案

使用 .iloc ,否则Pandas正在寻找一个标记为-1的索引键,该键不存在,因此为KeyError。

moving_average = df['score'].rolling(window=period).mean().iloc[-1]

07-24 09:52
查看更多