Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access the last element in a Pandas series?

Let us consider the following data frame:

import pandas as pd

d = {'col1': [1, 2, 3], 'col2': [3, 4, 5]}
df=pd.DataFrame(data=d)

If I want to access the first element in pandas series df['col1'], I can simply go df['col1'][0].

But how can I access the last element in this series? I have tried df['col1'][-1] which returns the following error:

KeyError: -1L

I know that I could go for something like df['col1'][len(df)-1] but why is reverse indexing impossible here?

like image 357
Sheldon Avatar asked May 24 '19 08:05

Sheldon


People also ask

How do you access the elements of a series in pandas?

Accessing Element from Series with PositionUse the index operator [ ] to access an element in a series. The index must be an integer. In order to access multiple elements from a series, we use Slice operation.

Which function will you use to display the last N items from a series object?

last() function to return the entries for the last 5 Days in the given series object.

How do you get the last value in a Dataframe in Python?

Get Cell Value from Last Row of Pandas DataFrame To select the cell value of the last row and last column use df. iloc[-1,-1] , this returns 2500 .


2 Answers

For select last value need Series.iloc or Series.iat, because df['col1'] return Series:

print (df['col1'].iloc[-1])
3
print (df['col1'].iat[-1])
3

Or convert Series to numpy array and select last:

print (df['col1'].values[-1])
3

Or use DataFrame.iloc or DataFrame.iat - but is necessary position of column by Index.get_loc:

print (df.iloc[-1, df.columns.get_loc('col1')])
3
print (df.iat[-1, df.columns.get_loc('col1')])
3

Or is possible use last value of index (necessary not duplicated) and select by DataFrame.loc:

print (df.loc[df.index[-1], 'col1'])
3
like image 138
jezrael Avatar answered Sep 26 '22 01:09

jezrael


You can also use tail:

print(df['col1'].tail(1).item())

Output:

3
like image 9
U12-Forward Avatar answered Sep 26 '22 01:09

U12-Forward