首页 > 解决方案 > 在一个单元格之后删除所有单元格

问题描述

您好,我有以下 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

我想将某个单元格之后的所有单元格更改为空字符串。

我试过下面的代码,想知道是否有更有效的方法来做到这一点

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        

谢谢

标签: pythonpandas

解决方案


尝试:

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

印刷:

        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            

推荐阅读