The Python Oracle

Pandas: Check if row exists with certain values

This video explains
Pandas: Check if row exists with certain values

--

Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Riding Sky Waves v001

--

Chapters
00:00 Question
00:50 Accepted answer (Score 97)
01:23 Answer 2 (Score 33)
01:36 Answer 3 (Score 12)
01:51 Answer 4 (Score 1)
02:13 Thank you

--

Full question
https://stackoverflow.com/questions/2476...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #pandas #contains

#avk47



ACCEPTED ANSWER

Score 106


Turns out it is really easy, the following does the job here:

>>> ((df['A'] == 2) & (df['B'] == 3)).any()
True
>>> ((df['A'] == 1) & (df['B'] == 2)).any()
False

Maybe somebody comes up with a better solution which allows directly passing in the array and the list of columns to match.

Note that the parenthesis around df['A'] == 2 are not optional since the & operator binds just as strong as the == operator.




ANSWER 2

Score 36


an easier way is:

a = np.array([2,3])
(df == a).all(1).any()



ANSWER 3

Score 14


If you also want to return the index where the matches occurred:

index_list = df[(df['A'] == 2)&(df['B'] == 3)].index.tolist()



ANSWER 4

Score 2


To find rows where a single column equals a certain value:

df[df['column name'] == value]

To find rows where multiple columns equal different values, Note the inner ():

df[(df["Col1"] == Value1 & df["Col2"] == Value2 & ....)]