A function like index.get_loc, but for multiple values

Viewed 876

I have the following data frame:

df = pd.DataFrame({'color': ['Yellow', 'Green', 'Red', 'Orange'], 'weight': [0.5, 4, 1, 10]}, index = ['Banana','Melon','Apple','Pumpkin'])

which looks like this:

Banana  Yellow     0.5
Melon    Green     4.0
Apple      Red     1.0
Pumpkin  Orange    10.0

What I'm trying to do is access the integer locations of a subset of 'Banana','Melon','Apple','Pumpkin'. I know that pandas.index.get_loc is a way of doing this for a single element of index. For example: df.index.get_loc('Apple') returns 2. However, I would like to do this for multiple elements at once. I tried, among other things, df.index.get_loc('Apple','Pumpkin'), hoping to get the list [2,3], but this gave the following error: ValueError: Invalid fill method. Expecting pad (ffill), backfill (bfill) or nearest. Got pumpkin

Is there a function that will allow me to get multiple integer locations at once?

1 Answers

Try with get_indexer which accept list like input

df.index.get_indexer(['Apple','Pumpkin'])
Out[104]: array([2, 3], dtype=int32)
Related