简体   繁体   中英

How to get the index of a value in a pandas series

What's the code to get the index of a value in a pandas series data structure?.

animals=pd.Series(['bear','dog','mammoth','python'], 
                  index=['canada','germany','iran','brazil'])

What's the code to extract the index of "mammoth"?

You can just use boolean indexing:

In [8]: animals == 'mammoth'
Out[8]:
canada     False
germany    False
iran        True
brazil     False
dtype: bool

In [9]: animals[animals == 'mammoth'].index
Out[9]: Index(['iran'], dtype='object')

Note, indexes aren't necessarily unique for pandas data structures.

You have two options:

1) If you make sure that value is unique, or just want to get the first one, use the find function.

find(animals, 'mammoth') #  retrieves index of first occurrence of value

2) If you would like to get all indices matching that value, as per @juanpa.arrivillaga 's post.

animals[animals == 'mammoth'].index # retrieves indices of all matching values

You can also index find any number occurrence of the value by treating the the above statement as a list:

animals[animas == 'mammoth'].index[1] #retrieves index of second occurrence of value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM