johny
johny

Reputation: 53

Finding list of index corresponding to list of element of a dataframe in Python

I have a dataframe with millions of lines. I need to get the corresponding indexes of hundreds of thousands of elements that are present in the original dataframe.

I currently use this code:

df[df['processed_col'] == element.index[0]

to find the position of 'element' into the whole dataframe.

Instead of doing a loop which is very long, is there a way to take a list like element1, element2,..., elementN as input, which would return a list of corresponding indices:

df[df['processed_col'] == [element1, element2, ..., elementN].index[0]

Upvotes: 2

Views: 2156

Answers (1)

jezrael
jezrael

Reputation: 862691

IIUC you need isin if find first value of index:

df[df['processed_col'].isin([element1, element2,..., elementN])].index[0]

or if want all values of index, remove [0] only:

df[df['processed_col'].isin([element1, element2,..., elementN])].index

If need convert to list use tolist:

df[df['processed_col'].isin([element1, element2,..., elementN])].index.tolist()

Upvotes: 3

Related Questions