How to change the first occurrence of 'True' in a row to false in pandas


How to change the first occurrence of 'True' in a row to false in pandas



I'm trying to change the first instance of True to False in my DataFrame dependent on row:


True


False


A B C
Number
1 True True True
2 False True True
3 False False True

A B C
Number
1 False True True
2 False False True
3 False False False



Every time I try using the for index, row in target_df.iterrows(): line it ends up never finding any 'True' when I look through the row.


for index, row in target_df.iterrows():



Thanks in advance!




1 Answer
1



You can use the cumulative sum of the Boolean values (False corresponds to 0; True to 1) for each row, along with DataFrame.mask():


DataFrame.mask()


>>> condition = df.cumsum(axis=1) == 1
>>> df.mask(condition, False)
a b c
0 False True True
1 False False True
2 False False False



df.mask(self, cond, other=nan)


df.mask(self, cond, other=nan)



Return an object of same shape as self and whose corresponding entries
are from self where cond is False and otherwise are from other.



In this case, condition is False everywhere except the points at which you want to switch True -> False:


condition


True


False


>>> condition
a b c
0 True False False
1 False True False
2 False False True



One other option would be to use NumPy:


>>> row, col = np.where(df.cumsum(axis=1) == 1)
>>> df.values[row, col] = False
>>> df
a b c
0 False True True
1 False False True
2 False False False






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

How to add background colour in existing image using Swift?

Moria Casán

How to make file upload 'Required' in Contact Form 7?