With Python lists you can slice with negative indices.
a = [1,2,3,4,5,6,7,8,9]
print(a[-1])
will print 9
as expected.
However,
a = pd.Series([1,2,3,4,5,6,7,8,9])
print(a[-1])
gives KeyError: -1L
To recap, Python supports positive zero-based indexing and negative indexing that starts from -1. Negative indexing in Python means the indexing starts from the end of the iterable.
Negative numbers mean that you count from the right instead of the left. So, list[-1] refers to the last element, list[-2] is the second-last, and so on.
Using iloc –You can use negative index to select a row when using iloc as this method is used to select rows and columns using index number.
Use iloc to get by position rather than label:
In [11]: a.iloc[-1]
Out[11]: 9
See selection section of the docs.
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