Mainland
Mainland

Reputation: 4554

Python Dataframe Check All rows equal to False

My dataframe has boolean values. I want to extract rows where all of them are False.

My code:

df = 
                               colA               colB
datetime                                            
2019-01-01 10:09:18            False             NaN
2019-01-01 10:10:55             True             NaN
2019-01-02 07:32:36             True            True
2019-01-02 13:32:29             True            True
2019-01-02 15:32:26             True           False
2020-17-23 18:44:45            False           False
2020-17-24 14:14:13             True            True
2020-17-24 18:44:44            False           False
2020-17-25 06:44:43            False           False
2020-17-25 14:14:13             True            True

# The following gives output True when all are True. I want True when all are False
print(df.all(1))

Present output:

datetime
2019-10-01 10:09:18    False
2019-10-01 10:10:55     True
2019-10-02 07:32:36     True
2019-10-02 13:32:29     True
2019-10-02 15:32:26     False
 
2020-07-23 18:44:45    False
2020-07-24 14:14:13     True
2020-07-24 18:44:44    False
2020-07-25 06:44:43    False
2020-07-25 14:14:13     True

The second row gives True for True and NaN, which is bad. It should actually give False here. The main thing I want to achieve is, True when all are False (not including NaNs)

Upvotes: 0

Views: 467

Answers (1)

Erfan
Erfan

Reputation: 42886

First fillna with True, then we use all over axis=1 and finally invert our outcome with ~:

~df.fillna(True).all(axis=1)

datetime
2019-01-01 10:09:18     True
2019-01-01 10:10:55    False
2019-01-02 07:32:36    False
2019-01-02 13:32:29    False
2019-01-02 15:32:26     True
2020-17-23 18:44:45     True
2020-17-24 14:14:13    False
2020-17-24 18:44:44     True
2020-17-25 06:44:43     True
2020-17-25 14:14:13    False

Upvotes: 1

Related Questions