我有一个名为moving_average
的蟒蛇熊猫系列。
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
答案 0 :(得分:8)
使用.iloc
,否则Pandas会查找标记为-1的索引键,因为KeyError不存在。
moving_average = df['score'].rolling(window=period).mean().iloc[-1]
答案 1 :(得分:5)
当您使用head()
时,请不要忘记tail()
df['score'].rolling(window=period).mean().tail(1)
答案 2 :(得分:2)
尝试:
moving_average = df['score'].rolling(window=period).mean().iloc[-1]
答案 3 :(得分:1)
您可以使用:
moving_average = df['score'].rolling(window = period).mean().iloc[-1]