To get the last element of a pandas series, the easiest way is to use iloc and access the ‘-1’ indexed element.

import pandas as pd

s = pd.Series([0,1,2,3])

print(s.iloc[-1])

#Output:
3

You can also use iat to get the last element of a pandas series.

import pandas as pd

s = pd.Series([0,1,2,3])

print(s.iat[-1])

#Output:
3

The last way to get the last element of a pandas series is with tail() and item().

import pandas as pd

s = pd.Series([0,1,2,3])

print(s.tail(1).item())

#Output:
3

When working with collections of data in Python, the ability to get particular elements easily is very important.

One such case is if you are using pandas and want to get the last element of a series.

There are a few different ways you can access the last element of a pandas series which we will cover in this article.

Using iloc() to Get Last Element of pandas Series in Python

The first and easiest way you can get the last element of a pandas series in Python is with iloc.

iloc allows us to access elements using purely integer-location based indexing for selection by position.

In other words, you can access elements by passing an integer representing the position of the element you want to access.

To get the last element, you can pass ‘-1’ to iloc.

Below shows you how to get the last element of a pandas series using iloc in Python.

import pandas as pd

s = pd.Series([0,1,2,3])

print(s.iloc[-1])

#Output:
3

Using iat() to Get Last Element of pandas Series in Python

Another way you can get the last element of a series when using pandas is with iat.

Similar to iloc, you can use iat to access a single value based on an integer location.

Below shows you how to get the last element of a pandas series using iat in Python.

import pandas as pd

s = pd.Series([0,1,2,3])

print(s.iat[-1])

#Output:
3

Using tail() to Get Last Element of pandas Series in Python

One last way you can get the last element of a pandas series object is with tail() and item().

The tail() function returns a specified number of elements from the end of a pandas series and then you can use item() to get the value of the last element.

Below is a simple example showing you how to get the last element of a pandas series with tail() and item().

import pandas as pd

s = pd.Series([0,1,2,3])

print(s.tail(1).item())

#Output:
3

Get First Element of pandas Series with iloc in Python

If you want to instead get the first element of a pandas series, you can use iloc and access the first element.

Below is an example showing you how to get first element of a pandas series in Python.

import pandas as pd

s = pd.Series([0,1,2,3])

print(s.iloc[0])

#Output:
0

Hopefully this article has been useful for you to be able to get the last element of a pandas series in Python.

Categorized in:

Python,

Last Update: March 12, 2024