Reputation: 2014
Let's assume we have a simple dataframe like this:
df = pd.DataFrame({'col1':[1,2,3], 'col2':[10,20,30]})
Then I can select elements like this
df.col2[0]
or df.col2[1]
But if I want to select the last element with df.col2[-1]
it results in the error message:
KeyError: -1
I know that there are workarounds to that. I could do for example df.col2[len(df)-1]
or df.iloc[-1,1]
. But why wouldn't be the much simpler version of indexing directly by -1
be allowed? Am I maybe missing another simple selection way for -1
? Tnx
Upvotes: 0
Views: 1377
Reputation: 4275
The index labels of your DataFrame are [0,1,2]. Your code df.col2[1]
is an equivalent of using a loc function as df['col2'].loc[1]
(or df.col2.loc[1]
). You can see that you index does not contain a label '-1' (which is why you get the KeyError).
For positional indexing you need to use an iloc function (which you can use on Pandas Series as well as DataFrame), so you could do df['col2'].iloc[-1]
(or df.col2.iloc[-1]
).
As you can see, you can use both label based ('col2') and position based (-1) indexing together, you don't need to choose one or another as df.iloc[-1,1]
or df.col2[len(df)-1]
(which would be equivalent to df.loc[lend(df)-1,'col2']
)
Upvotes: 3