I have a python panda series called moving_average
.
moving_average = df['score'].rolling(window=period).mean()
I would like to retrieve the last element of Series moving_average
. This is what I did.
moving_average = df['score'].rolling(window=period).mean()[-1]
Unfortunately, I got the following error.
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
I am using python v3.6
Python3. Pandas iloc is used to retrieve data by specifying its integer index. In python negative index starts from end therefore we can access the last element by specifying index to -1 instead of length-1 which will yield the same result.
Accessing Element from Series with Position In order to access the series element refers to the index number. Use the index operator [ ] to access an element in a series. The index must be an integer. In order to access multiple elements from a series, we use Slice operation.
last() function to return the entries for the last 5 Days in the given series object.
To get the last element of the list in Python, use the list[-1] syntax. The list[-n] syntax gets the nth-to-last element. So list[-1] gets the last element, and list[-2] gets the second to last. The list[-1] is the most preferable, shortest, and Pythonic way to get the last element.
Use .iloc
, otherwise Pandas is looking for an index key labelled as -1 which doesn't exist hence the KeyError.
moving_average = df['score'].rolling(window=period).mean().iloc[-1]
When you are using head()
do not forget tail()
df['score'].rolling(window=period).mean().tail(1)
Try:
moving_average = df['score'].rolling(window=period).mean().iloc[-1]
You can use:
moving_average = df['score'].rolling(window = period).mean().iloc[-1]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With