Home > Back-end >  Pandas modify value after first N True value
Pandas modify value after first N True value

Time:03-13

I have the following to tables of boolean values:

df1 = pd.DataFrame(data={'v': [True, True, True],
                         'w': [True, False, False], 
                         'x': [False, True, False],
                         'y': [True, True, True],
                         'z': [True, False, True]},
                         index=pd.Series([1, 2, 3], name='index'))
index v w x y z
1 True True False True True
2 True False True True False
3 True False False True True

After n first True values in each row, how can I turn rest of the values into False? For example, if n was 2:

index v w x y z
1 True True False False False
2 True False True False False
3 True False False True False

Row row 1, x and y would turn to False, since v and w are True.

CodePudding user response:

Try with where and cumsum

n = 2
out = df1.where(df1.cumsum(axis=1)<=n,False)
Out[24]: 
          v      w      x      y      z
index                                  
1      True   True  False  False  False
2      True  False   True  False  False
3      True  False  False   True  False
  • Related