Search code examples
pythonfor-loopfilterdrop

Drop rows where all Boolean columns are False - Python


How do I drop a row if all rows have the value False? (here it would mean dropping 'kiwi'.)

print(df.head())

>   concatenated   category    apple  banana  orange
> 0  apple_banana    two        True    True   False
> 1        apple     one        True   False   False
> 2        banana    one        False   True   False
> 3        kiwi      one        False   False  False


Solution

  • You can iterate through each row in the df and compare the column, if you get 3 False then you can drop the row,

     for index, row in df.iterrows():
        if not row["apple"] and  not row["banana"] and not row["orange"]:
            df.drop(index=index, inplace=True)
               
    

    Try this also

      df1 = df[~(~(df['banana'])& ~(df['apple']) & ~(df['orange']))]  
    

    Answer for your last commend

      boolean_columns = ['apple', 'banana', 'orange']
      x = " & ".join('~('+x+')' for x in boolean_columns) 
      x = "~("+x+")"
      df1 = df.query(x)   
    

    Try this