You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何删除Pandas DataFrame中存在多个1的行?

解决Pandas删除多列含多个1的行的问题

原始数据

我们有如下的Pandas DataFrame:

Itemsnotebookballpointpencileraserpencil sharpenerstaplerpaperscissorsglue
image1101100000
image2010000100
image3000010000
image4000001000
image5000000010

需求

删除那些在不同列中存在多个1的行,只保留恰好只有一个1的行。

解决方案

核心思路是计算每行中1的数量,筛选出数量等于1的行:

  1. 排除Items列,计算剩余列每行的和(因为列值都是0或1,求和结果就是该行中1的个数)
  2. 筛选出求和结果等于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如下:

Itemsnotebookballpointpencileraserpencil sharpenerstaplerpaperscissorsglue
image3000010000
image4000001000
image5000000010

内容的提问来源于stack exchange,提问作者takupasmeong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 19:38:19