Find element's index in pandas Series

444    Asked by JyotiSharma in Salesforce , Asked on Jul 7, 2021

 I know this is a very basic question but for some reason I can't find an answer. How can I get the index of certain element of a Series in python pandas? (first occurrence would suffice)

I.e., I'd like something like:

import pandas as pd
myseries = pd.Series([1,4,0,7,5], index=[0,1,2,3,4])
print myseries.find(7) # should output 3

Certainly, it is possible to define such a method with a loop:

def find(s, el):
    for i in s.index:
        if s[i] == el: 
            return i
    return None
print find(myseries, 7)

but I assume there should be a better way. How to get index of series pandas?


Answered by jack Burgess

To find element index in pandas series, use this:

 myseries[myseries == 8]
3 8
dtype: int64
myseries[myseries == 8].index[0]
3

Note: In order to access the series element use 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.



Your Answer

Interviews

Parent Categories