如何用Pandas检测DataFrame同一行多列同时为True的情况
问题描述
我有如下结构的DataFrame:
| Column A | Column B | Column C | Column D |
|---|---|---|---|
| 1 | True | False | False |
| 2 | False | True | False |
| 3 | False | False | True |
| 4 | True | False | True |
| 5 | False | True | True |
| 6 | False | False | False |
| 7 | False | True | False |
需要检查是否存在同一行包含两个及以上True值的情况:预期每行最多一个True,全False或单个True均符合要求,同一行有两个及以上True则属于异常。由于后续要统计True的数量,多True会导致同一事件被重复计数,因此需要筛选出这些异常行,期望输出结果如下:
| Column A | Column B | Column C | Column D |
|---|---|---|---|
| 4 | True | False | True |
| 5 | False | True | True |
解决方案
通过计算每行中True的数量,筛选出数量≥2的行即可:
import pandas as pd # 构造示例DataFrame df = pd.DataFrame({ 'Column A': [1, 2, 3, 4, 5, 6, 7], 'Column B': [True, False, False, True, False, False, False], 'Column C': [False, True, False, False, True, False, True], 'Column D': [False, False, True, True, True, False, False] }) # 统计每行B、C、D列的True数量,筛选出数量≥2的行 anomalous_rows = df[df[['Column B', 'Column C', 'Column D']].sum(axis=1) >= 2] print(anomalous_rows)
运行代码后得到的输出即为目标异常行:
| Column A | Column B | Column C | Column D |
|---|---|---|---|
| 4 | True | False | True |
| 5 | False | True | True |
内容的提问来源于stack exchange,提问作者U.K.Owen
相关产品推荐
相关产品推荐

