Jawsh
Jawsh

Reputation: 466

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:

              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.

Thanks in advance!

Upvotes: 3

Views: 1188

Answers (1)

Brad Solomon
Brad Solomon

Reputation: 40908

You can use the cumulative sum of the Boolean values (False corresponds to 0; True to 1) for each row, along with 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)

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

Upvotes: 4

Related Questions