1

I want to find indexes of some rows same as a array from pandas dataframe.

My dataframe is like below

df = pd.DataFrame({'a':[True, False, True, True],'b':[False, True, True, True],'c':[True, True, False, True],'d':[True, False, True, False]})

the input value that I'll enter is like row = [True, True, False, True], and I want get [2].

I tried some with for like this

index = []
for i in range df.shape[0]:
    if df.iloc[i,:].tolist() == row
        index.append(i)

It works but extremely slow for my work. Is there any method for this?

1 Answer 1

4

Use DataFrame.eq and Series.all:

df[df.eq(row).all(1)]

Example

df = pd.DataFrame({'a':[True, False, True, True],'b':[False, True, True, True],'c':[True, True, False, True],'d':[True, False, True, False]})
row = [True, True, False, True]

df[df.eq(row).all(1)]

[out]

      a     b      c     d
2  True  True  False  True 

If needed, chain on index.to_list() for list of indices:

df[df.eq(row).all(1)].index.to_list()

[2]
Sign up to request clarification or add additional context in comments.

1 Comment

@Luterino no problem buddy, glad it helps

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.