The Python Oracle

Pandas: Check if row exists with certain values

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: The World Wide Mind

--

Chapters
00:00 Pandas: Check If Row Exists With Certain Values
00:38 Accepted Answer Score 106
01:05 Answer 2 Score 36
01:15 Answer 3 Score 14
01:27 Answer 4 Score 2
01:41 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 & ....)]