The Python Oracle

Find first true value in a row of Pandas dataframe

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: Lost Jungle Looping

--

Chapters
00:00 Question
01:35 Accepted answer (Score 9)
02:12 Answer 2 (Score 1)
02:32 Answer 3 (Score 1)
02:59 Thank you

--

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

--

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

--

Tags
#python #pandas

#avk47



ACCEPTED ANSWER

Score 9


One way would be to use cumsum to help find the first:

In [123]: (b1 & b2 & (b2.cumsum(axis=1) == 1)).any(axis=1)
Out[123]: 
0     True
1     True
2    False
3    False
dtype: bool

This works because b2.cumsum(axis=1) gives us the cumulative number of Trues seen, and cases where that number is 1 and b2 itself is True must be the first one.

In [124]: b2.cumsum(axis=1)
Out[124]: 
   0  1  2  3  4
0  1  1  2  2  2
1  0  0  1  2  3
2  1  2  2  2  2
3  1  2  3  3  3



ANSWER 2

Score 1


As a variation to @DSM's clever answer, this approach seemed a little more intuitive to me. The first part should be pretty self-explanatory, and the second part finds the first column number (w/ axis = 1) that is true for each dataframe and compares.

(b1.any(axis = 1) & (b1.idxmax(axis = 1) == b2.idxmax(axis = 1))



ANSWER 3

Score 1


Worked out a solution which turned out to be similar to pshep123's solution.

# the part on the right of & is to check if the first True position in b1 matches the first True position in b2.

b1.any(1) & (b1.values.argmax(axis=1) == b2.values.argmax(axis=1))
Out[823]: 
0     True
1     True
2    False
3    False
dtype: bool