Python:根据特定条件删除单元格的内容

Python:根据特定条件删除单元格的内容,python,pandas,Python,Pandas,我有一个*.xlsx文件,如下所示- A B C [['Neutral']] ['nan'] [['Neutral']] ['nan'] Bad

我有一个*.xlsx文件,如下所示-

           A                              B                        C
                                   [['Neutral']]                ['nan']
                                   [['Neutral']]                ['nan']
          Bad                      [['Negative']]               ['Bad']
          Meh                      [['Neutral']]                ['Meh']
                                   [['Neutral']]                ['nan']
我正在尝试删除列
B
C
中的所有
[['Neutral']]和['nan']
值,仅当它们的值为
null

这是我的密码-

df1 = pd.read_excel(path)

for i, row in df1.iterrows():
    if pd.isnull(row[0]):
        # del row[1]
        # del row[2]
        row[1] = 0
        row[2] = 0
我的代码完美地找到了所有空值,但无法清除
B
C
列变量s。我做错了什么

预期产量为-

       A                              B                        C


      Bad                      [['Negative']]               ['Bad']
      Meh                      [['Neutral']]                ['Meh']

是的,空白空间/单元格应该仍然存在。

试试这个,

mask=df['A'].isnull()
df.loc[mask]=''
输出:

     A               B        C
0                              
1                              
2  Bad  [['Negative']]  ['Bad']
3  Meh   [['Neutral']]  ['Meh']
4                              
对于这个问题,您不需要在pandas中使用For循环

解释

  • 查找A为空的位置的索引

  • 在选定索引处替换为空

  • 编辑:

    要从特定列中删除

    df.loc[mask,['B','C']]=''
    

    您可以通过获取空值的索引来简单地分配它

    df.loc[df.A.isnull()] = ''
    
    输出:


    有什么方法可以让我更具体一点吗?它可以工作,但也会删除其他列中的行。我是否可以指定,如果A为null,那么它应该删除B列中的行而不是C列
            A   B   C
    0           
    1           
    2   Bad [['Negative']]  ['Bad']
    3   Meh [['Neutral']]   ['Meh']
    4