The Python Oracle

counting the amount of True/False values in a pandas row

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: Luau

--

Chapters
00:00 Question
00:36 Accepted answer (Score 12)
01:11 Thank you

--

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

--

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

--

Tags
#python #pandas #dataframe

#avk47



ACCEPTED ANSWER

Score 12


You can do this:

df[(df > 3).sum(axis=1) >= 3]

where df > 3 returns a Boolean mask over the entire DataFrame according to the condition, and sum(axis=1) returns the number of True in that mask, for each row. Finally the >=3 operation returns another mask that can be used to filter the original DataFrame.

Output:

   A  B  C  D  E
b  3  6  5  8  8
c  6  2  5  5  2