3

How can I quickly drop rows where A, B and C are all false? I tried:

df3 = df[~(~(df['A'])& ~(df['B']) & ~(df['C']) )]
df3
   com     A        B           C
0  as     TRUE    FALSE       FALSE
1  da     TRUE    FALSE       FALSE

0

3 Answers 3

5

drop rows where A, B and C are are all false

With df.sum across axis=1 along with comparison if sum in the row for these coumns is not equal to 0 , using df.ne

out = df[df[['A','B','C']].sum(1).ne(0)].copy()
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks! Would you mind explaining this sorry? I didn't quite follow.
@asd when you take sum of each row for columns A,B,C , if there is any True value, it will return 1 or more , hence I check if the sum is not equal to zero (which means all columns for a row is False)
Thanks. Out of curiosity, what's wrong with the code I wrote? Am I misunderstanding some syntax or?
@asd what you do is False&False&False (which is False) ( assuming all the columns in the row is False) , then you invert it (~) which will always return True so for rows having all False values it still returns True and hence doesnot drop it
4

Wait a mins any

df[df[['A','B','C']].any(1)]

2 Comments

This is the easiest built-in way..!!
100% agree, I completely over-thought this one 😂
2

An alternative using all along axis 1. The 2nd ~ operator directly - directly before df, reversed all False to True. all returns True if all column values are True, then using ~ again to reverse this to index rows that are actually all False:

df3 = df[~(~df[['A', 'B', 'C']]).all(1)]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.