'Negative index in pandas give a KeyError unlike lists

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



Solution 1:[1]

Use iloc to get by position rather than label:

In [11]: a.iloc[-1]
Out[11]: 9

See selection section of the docs.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 wjandrea