Error Indexing Pandas Series Last Element in Python

I am attempting to access the last element (datetime) in my Pandas series. Below I am showing the type for clarification. I am new to Python so I apologize.

type(East.times)
pandas.core.series.Series

I am able to index the first element by doing East.times[0] where the output is

Timestamp('2017-09-01 00:00:00')

For reference, East.times outputs

0      2017-09-01 00:00:00
1      2017-09-01 00:05:00
2      2017-09-01 00:10:00
3      2017-09-01 00:15:00
4      2017-09-01 00:20:00
               ...        
8635   2017-09-30 23:35:00
8636   2017-09-30 23:40:00
8637   2017-09-30 23:45:00
8638   2017-09-30 23:50:00
8639   2017-09-30 23:55:00
Name: times, Length: 8640, dtype: datetime64[ns]

I want to index the last element by doing

East.times[-1]

However, I get the following error and I don’t understand why it won’t work.

KeyError                                  Traceback (most recent call last)
<ipython-input-37-7203880275dc> in <module>
----> 1 East.times[-1]

~Anaconda3libsite-packagespandascoreseries.py in __getitem__(self, key)
   1066         key = com.apply_if_callable(key, self)
   1067         try:
-> 1068             result = self.index.get_value(self, key)
   1069 
   1070             if not is_scalar(result):

~Anaconda3libsite-packagespandascoreindexesbase.py in get_value(self, series, key)
   4728         k = self._convert_scalar_indexer(k, kind="getitem")
   4729         try:
-> 4730             return self._engine.get_value(s, k, tz=getattr(series.dtype, "tz", None))
   4731         except KeyError as e1:
   4732             if len(self) > 0 and (self.holds_integer() or self.is_boolean()):

pandas_libsindex.pyx in pandas._libs.index.IndexEngine.get_value()

pandas_libsindex.pyx in pandas._libs.index.IndexEngine.get_value()

pandas_libsindex.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas_libshashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

pandas_libshashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

KeyError: -1

Answer

You want to use iloc here to get row based off index.

East.times.iloc[-1]

Leave a Reply

Your email address will not be published. Required fields are marked *