Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 523
john.r.woodward Avatar asked Nov 03 '15 16:11

john.r.woodward


People also ask

Do Python lists support negative indexing?

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.

What does negative index in a list indicate?

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.

Can you pass negative value ILOC?

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.


1 Answers

Use iloc to get by position rather than label:

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

See selection section of the docs.

like image 95
Andy Hayden Avatar answered Oct 10 '22 06:10

Andy Hayden