如何在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
相关产品推荐
相关产品推荐

