Get the row number from given indeces in Pandas

Viewed 49
import pandas as pd
df = pd.DataFrame({'A':[1,2,3], 'B':[4,5,6]}, 
                  index=['first','second','third'])

Retrieving the corresponding indeces from a given list of row numbers is simple:

df.iloc[[1,2]].index

But what about the converse? Suppose I am given a list ['second','third']. How can I return df's row numbers 0 and 1 from that?

2 Answers

Try:

df.index.get_indexer(['second', 'third'])

Output:

array([1, 2], dtype=int64)

We have get_indexer_for as well

df.index.get_indexer_for(['second', 'third'])
Out[178]: array([1, 2], dtype=int32)

And for get the value do index slice only is good enough, not need to filter the dataframe

df.index[[1,2]]
Out[181]: Index(['second', 'third'], dtype='object')
Related