How to find element’s index in pandas Series?

In this article, we will discuss multiple ways to find an element’s index in the pandas Series.

Table of Content

Preparing dataset

To quickly get started, let’s create a sample pandas Series for experimentation.

import pandas as pd
import numpy as np

new_series = pd.Series([1,4,0,7,5,4,9], index=[0,1,2,3,4,5,6])

print(new_series)

Content of the created Series is,

0    1
1    4
2    0
3    7
4    5
5    4
6    9
dtype: int64

Find index of an element in pandas Series using index attribute

The simplest way to find the element’s index is to filter for the specific element and use the index property of the pandas Series. For example, to get the index of element “0” from the above pandas Series, we can do the following

# get the index of element "0"
indexPos = new_series[new_series==0].index[0]

print(indexPos)

Output

2

To break down the code, we first filtered the Series to find the element “0” and then used the “.index” to get the index values of the same.

In case of multiple values, the index attribute will return all the matched indexes, from which we can select the nth value. To understand better, let’s find the index of the element “4”.

# get the indices of element "4"
indexValues = new_series[new_series==4].index

print(indexValues)

Output

Int64Index([1, 5], dtype='int64')

As observed, the element “4” is present on the index 1 and 5 both. We can select the desired index by passing it in the list element (“[n]”) as above.

Find index of an element in pandas Series using get_loc() method

Another method is to use “get_loc()” method to get the index of the desired element. Let’s understand with an example, by finding the index of the element “0”.

# get the index of element "0"
indexPos = pd.Index(new_series).get_loc(0)

print(indexPos)

Output

2

Here, we have first converted the series into pandas Index object and then used “get_loc” function to get the location of the “0” element.

Find index of an element in pandas Series using numpy.where() function

Another way is to use the numpy.where function to get the element’s index. Let’s understand with the same example as above.

# get the index of element "0"
indexPos = np.where(new_series== 0)[0][0]

print(indexPos)

Output

2

We have similar output as the above methods.

Summary

Today we learned about different techniques to find an element’s index in pandas Series in Python. Thanks.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top