如何删除Pandas DataFrame中存在多个1的行?
解决Pandas删除多列含多个1的行的问题
原始数据
我们有如下的Pandas DataFrame:
| Items | notebook | ballpoint | pencil | eraser | pencil sharpener | stapler | paper | scissors | glue |
|---|---|---|---|---|---|---|---|---|---|
| image1 | 1 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 |
| image2 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 |
| image3 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 |
| image4 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 |
| image5 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 |
需求
删除那些在不同列中存在多个1的行,只保留恰好只有一个1的行。
解决方案
核心思路是计算每行中1的数量,筛选出数量等于1的行:
- 排除
Items列,计算剩余列每行的和(因为列值都是0或1,求和结果就是该行中1的个数) - 筛选出求和结果等于1的行
代码实现
import pandas as pd # 构造原始DataFrame data = { 'Items': ['image1', 'image2', 'image3', 'image4', 'image5'], 'notebook': [1, 0, 0, 0, 0], 'ballpoint': [0, 1, 0, 0, 0], 'pencil': [1, 0, 0, 0, 0], 'eraser': [1, 0, 0, 0, 0], 'pencil sharpener': [0, 0, 1, 0, 0], 'stapler': [0, 0, 0, 1, 0], 'paper': [0, 1, 0, 0, 0], 'scissors': [0, 0, 0, 0, 1], 'glue': [0, 0, 0, 0, 0] } df = pd.DataFrame(data) # 筛选出仅含一个1的行 filtered_df = df[df.drop('Items', axis=1).sum(axis=1) == 1]
处理后结果
执行代码后得到的DataFrame如下:
| Items | notebook | ballpoint | pencil | eraser | pencil sharpener | stapler | paper | scissors | glue |
|---|---|---|---|---|---|---|---|---|---|
| image3 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 |
| image4 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 |
| image5 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 |
内容的提问来源于stack exchange,提问作者takupasmeong
相关产品推荐
相关产品推荐

