I am using python 3.6, pandas 24.2 and came across a difference.
>>> x = pd.Series(range(3))
>>> x[-1]
>>> x = pd.Series(range(3), index=[0,1,2])
>>> x[-1]
both produce an error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/conda3/ml4t/lib/python3.6/site-packages/pandas/core/series.py", line 868, in __getitem__
result = self.index.get_value(self, key)
File "/opt/conda3/ml4t/lib/python3.6/site-packages/pandas/core/indexes/base.py", line 4375, in get_value
tz=getattr(series.dtype, 'tz', None))
File "pandas/_libs/index.pyx", line 81, in pandas._libs.index.IndexEngine.get_value
File "pandas/_libs/index.pyx", line 89, in pandas._libs.index.IndexEngine.get_value
File "pandas/_libs/index.pyx", line 132, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/hashtable_class_helper.pxi", line 987, in pandas._libs.hashtable.Int64HashTable.get_item
File "pandas/_libs/hashtable_class_helper.pxi", line 993, in pandas._libs.hashtable.Int64HashTable.get_item
KeyError: -1
while
>>> x = pd.Series(range(3), index=['a','b','c'])
>>> x[-1]
2
is fine along with any other form of index. They are the same data structure but adding certain types of an index allows negative indexing while others don't?
For using a negative index, you can use:
x.iloc[-1]
This would work in all the cases.
Yes, the error is due to consistency issue as mentioned by @a-arnold.
Since indexing with [] must handle a lot of cases, we can't use such index always.
And when you set a custom index as string, the negative index works as it does not conflict with the integer index.
The Indexing and selecting data — pandas 1.0.3 documentation gives pretty good idea about indexing and selection in pandas.
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