drop all cells after a cell

Viewed 94

Hello I have the following DataFrame df:

A           B         C        D         E        F 
apple       0        red    green      blue      8
orange      2        red    blue       white     10
apple       2        red    green      blue      8
orange      0        red    20       purple     10

I would like to change all cells following a certain cell to empty strings.

I have tried the following code and was wondering if there is a more efficient way to do this

for i in range(len(df['B']):
    if df['B'].iloc[i] == 0:
        df['C'].iloc[i] = ""
        df['D'].iloc[i] = ""
        df['E'].iloc[i] = ""
        df['F'].iloc[i] = ""
 A           B         C        D         E        F 
apple       0        
orange      2        red    blue       white     10
apple       2        red    green      blue      8
orange      0        

Thank you

2 Answers

Try:

df.loc[df['B']==0,'C': ] = ''

Prints:

        A  B    C      D      E   F
0   apple  0                       
1  orange  2  red   blue  white  10
2   apple  2  red  green   blue   8
3  orange  0            

Just mask here.

df.loc[:, 'C':].mask(df['B'].eq(0), '')

     C      D      E   F
0                       
1  red   blue  white  10
2  red  green   blue   8
3                       
Related