2017-10-11 3 views
2

私はmoving_averageと呼ばれるpython pandaシリーズを持っています。このpython pandaの最後の要素にアクセスする系列

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 

私はそうパンダが故にKeyError例外存在しない-1としてラベルインデックスキーを探している、PythonのV3.6

答えて

4

使用.ilocを使用しています。

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

を忘れないでくださいLOL :-) – 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()を使用している私は2つの同じ答えを見たtail()

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

:)あなたは違っていなければなりません。 +1 –

+0

@ScottBostonがあなたに投票しました:-) – Wen

+0

@Wen、答えに感謝します。 tailを使用すると、単なる数値以上のものが返されます。名前とdtypeも返します。私が私の文脈で必要とする以上のもの。しかし、確かに知っておくと便利です。ありがとう。 – user781486

関連する問題