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

如何在Pandas中排除指定前缀列?报错原因及解决方法

问题解析与解决方案

报错原因

你定义的cols是一个字符串列表(比如['deathDay', 'deathMonth', 'deathYear']),但~是按位取反运算符,它只能作用于布尔数组或整数,没办法直接对列表使用,这就是触发bad operand type for unary ~: 'list'错误的原因。

实现需求的几种方法

方法1:直接生成要保留的列名列表

通过列表推导式筛选出所有不以"death"开头的列,直接索引DataFrame:

keep_cols = [col for col in df.columns if not col.startswith("death")]
df = df[keep_cols]

方法2:用布尔掩码筛选列

利用df.columns.str.startswith()生成布尔数组,取反后通过loc筛选列:

df = df.loc[:, ~df.columns.str.startswith("death")]

方法3:用drop删除目标列

先生成要删除的列名列表,再调用drop方法移除这些列:

drop_cols = [col for col in df.columns if col.startswith("death")]
df = df.drop(columns=drop_cols)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 14:47:07