2017-10-11 84 views
2

我有一个叫做moving_average的python熊猫系列。访问这个python熊猫系列的最后一个元素

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

回答

4

使用.iloc,否则熊猫正在寻找标记为-1索引键不存在,因此在KeyError异常。

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

我看到了两个相同的答案哈哈:-) – Wen

2

尝试:

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

1

您可以使用:

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

当您使用head()不要忘记tail()

df['score'].rolling(window=period).mean().tail(1) 
+0

:)你必须有所不同。 +1 –

+0

@ScottBoston已经投票给你了:-) – Wen

+0

@Wen,谢谢你的回答。使用尾巴不仅仅是一个数字。它还返回名称和dtype。超过我在我的情况下所需要的。但是,知道它肯定是有用的。谢谢。 – user781486