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

import pandas as pd

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

print(s.iloc[0])

#Output:
0

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

import pandas as pd

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

print(s.iat[0])

#Output:
0

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

import pandas as pd

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

print(s.head(1).item())

#Output:
0

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 first element of a series.

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

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

The first and easiest way you can get the first 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 first element, you can pass ‘0’ to iloc.

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

import pandas as pd

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

print(s.iloc[0])

#Output:
0

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

Another way you can get the first 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 first element of a pandas series using iat in Python.

import pandas as pd

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

print(s.iat[0])

#Output:
0

Using head() to Get First Element of pandas Series in Python

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

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

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

import pandas as pd

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

print(s.head(1).item())

#Output:
0

Get Last Element of pandas Series with iloc in Python

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

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

import pandas as pd

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

print(s.iloc[-1])

#Output:
3

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

Categorized in:

Python,

Last Update: March 11, 2024