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

Pandas如何删除特定分类变量对应行中值全为0的记录

Pandas 实现指定行过滤方案

你可以通过组合布尔条件筛选的方式完成需求,核心逻辑是标记需要删除的行后取反保留剩余数据,代码如下:

import pandas as pd

# 构造示例数据,如果你已经有原始DataFrame可以跳过这部分
df = pd.DataFrame({
    'Variable': ['A', 'B', 'C', 'D', 'A', 'B', 'C'],
    'Value1': [1, 1, 2, 4, 0, 0, 0],
    'Value2': [2, 5, 4, 2, 0, 0, 0],
    'Value3': [3, 6, 3, 1, 0, 0, 0]
})

# 标记需要删除的行:Variable为B/C 且 三个Value值均为0
drop_mask = df['Variable'].isin(['B', 'C']) & (df[['Value1', 'Value2', 'Value3']] == 0).all(axis=1)
# 取反保留不需要删除的行
result_df = df[~drop_mask]

如果需要直接修改原DataFrame,可以用drop方法:

df.drop(df[drop_mask].index, inplace=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 13:54:04