How to access the last element in a Pandas series?

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

To take last through values is the most quick way:

%timeit df['code'].values[-1].   )

5.58 µs ± 985 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit df.loc[df.index[-1], 'code']

12 µs ± 2.71 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit df['code'].iat[-1]

5.71 µs ± 896 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit df['code'].tail(1).item()

36 µs ± 3.23 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

%timeit df.iloc[-1, df.columns.get_loc('code')]

33.7 µs ± 5.23 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

%timeit df['code'].iloc[-1]

8.08 µs ± 496 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)


Alternatively you can use take:

In [6]: df['col1'].take([-1]).item()
Out[6]: 3

You can also use tail:

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

Output:

3