How to delete cells and cut rows find by " ̶i̶s̶i̶n̶(̶)̶ " df.mask()?

Viewed 40

I have dataframe with random cells, for example "boss". How can I delete the cells "boss" and all right cells in the same row using df.isin()?

x=[]
for i in range (5):
    x.append("boss")
df=pd.DataFrame(np.diagflat(x) ) 

      0     1     2     3     4
0  boss                        
1        boss                  
2              boss            
3                    boss      
4                          boss

cut rows using "i̶s̶i̶n̶(̶)̶ " df.mask to

mask=(df.eq('boss').cumsum(axis=1).ne(0))
df.mask(mask,"Nan", inplace =True)

df
     0    1    2    3    4
0  NaN  NaN  NaN  NaN  NaN          
1       NaN  NaN  NaN  NaN
2            NaN  NaN  NaN  
3                 NaN  NaN 
4                      NaN
1 Answers

Use DataFrame.mask with mask:

df = df.mask(df.eq('boss').cumsum(axis=1).ne(0))
print (df)
     0    1    2    3    4
0  NaN  NaN  NaN  NaN  NaN
1       NaN  NaN  NaN  NaN
2            NaN  NaN  NaN
3                 NaN  NaN
4                      NaN

Details:

Compare value boss:

print (df.eq('boss'))
       0      1      2      3      4
0   True  False  False  False  False
1  False   True  False  False  False
2  False  False   True  False  False
3  False  False  False   True  False
4  False  False  False  False   True

Use cumulative sum per rows, so after first match get 1, after second 2..:

print (df.eq('boss').cumsum(axis=1))
   0  1  2  3  4
0  1  1  1  1  1
1  0  1  1  1  1
2  0  0  1  1  1
3  0  0  0  1  1
4  0  0  0  0  1

Compare if not equal 0 and pass to mask:

print (df.eq('boss').cumsum(axis=1).ne(0))
       0      1      2      3     4
0   True   True   True   True  True
1  False   True   True   True  True
2  False  False   True   True  True
3  False  False  False   True  True
4  False  False  False  False  True
Related