You need to enable JavaScript to run this app. 如何对比DataFrame与指定列表,删除Lien列包含列表值的所有行
优惠活动
大模型
产品
解决方案
定价
更多

如何对比DataFrame与指定列表,删除Lien列包含列表值的所有行

实现方法

假设你需要排除的字符串列表名为 excluded_liens,示例定义如下:

# 替换为你实际的排除列表内容
excluded_liens = ["https://example.com/1", "https://test.cn/xxx", ...]

方案1:生成新的DataFrame(不修改原始数据,推荐)

利用pandas的isin()方法匹配属于排除列表的行,取反后筛选即可得到符合要求的新DataFrame:

new_df = df[~df["Lien"].isin(excluded_liens)]

其中~是pandas中的按位取反运算符,作用是筛选出Lien列取值不在排除列表中的行。

方案2:直接修改原始DataFrame

如果不需要保留原始数据,可以直接修改原对象,两种常用写法:

  • 直接覆盖原变量:
df = df[~df["Lien"].isin(excluded_liens)]
  • 用drop方法删除匹配行(指定inplace=True直接修改原对象):
df.drop(df[df["Lien"].isin(excluded_liens)].index, inplace=True)

常见问题补充

如果Lien列的字符串存在前后空格、大小写不一致等情况导致匹配失效,可以先做一次清洗再筛选:

# 先去除Lien列的前后空格,再进行匹配
df["Lien"] = df["Lien"].str.strip()
new_df = df[~df["Lien"].isin(excluded_liens)]

你可以执行以下代码验证结果,如果输出为空DataFrame说明所有待排除的行都已经被清理:

print(new_df[new_df["Lien"].isin(excluded_liens)])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 23:45:02