1

So far I am getting the index of first matching record for a particular value in the Python data frame column. I get it using the code below :

df1.loc[df1.Column1 == 'word1'].index.tolist()[0]

Suppose if 'word1' is present four times in the data frame for example in the index positions : 3, 7, 9, 14, the above command will return me the answer as 3

Now I need to check the same with multiple values for the column and the output should be the first matching index of any of those values.

I tried with few options as shown below but in vain.

df1.loc[df1.Column1 == 'word1'|'word2'].index.tolist()[0]
df1.loc[df1.Column1 == 'word1','word2'].index.tolist()[0]
df1.loc[df1.Column1 == 'word1' or 'word2'].index.tolist()[0]

Any idea on how to check for multiple values here ?

1 Answer 1

3

You need isin for condition:

df1.loc[df1.Column1.isin(['word1','word2'])].index.tolist()[0]

Simplier solution with idxmax for get index of first max value, because Trues are handle like 1s:

print (df1.Column1.isin(['word1','word2']))
0    False
1    False
2    False
3     True
4    False
5    False
6     True
7    False
Name: Column1, dtype: bool

df1.Column1.isin(['word1','word2']).idxmax()

Or with numpy.where:

np.where(df1.Column1.isin(['word1','word2']))[0][0]

Sample:

df1 = pd.DataFrame({ 'Column1':['s','g','h','word2','d','f','word1','d']})

a = df1.Column1.isin(['word1','word2']).idxmax()
print (a)
3
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much. But can you please shed more light on idxmax. By its name I assume there must be something called idxmin as well.
Yes, df1.Column1.isin(['word1','word2']).idxmin() return first False index, test it by df1 = pd.DataFrame({ 'Column1':['word2','g','h','word2','d','f','word1','d']})

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.