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

如何删除df1中col2值未出现在df2 col1中的行

删除DataFrame中指定列值不在另一DataFrame中的行

示例数据构建

先将示例数据转换成可运行的pandas代码:

import pandas as pd

df1 = pd.DataFrame({
    'col1': ['abcdef', 'abcdef1'],
    'col2': ['ghijkl', 'ghijkl1'],
    'col3': ['mnopqr', 'mnopqr1']
})

df2 = pd.DataFrame({
    'col1': ['ghijkl1']
})

核心解决方案

使用pandas的isin()方法快速筛选符合条件的行,该方法会检查df1['col2']的每个值是否存在于df2['col1']的取值集合中:

# 筛选并保留符合条件的行,生成新的DataFrame
filtered_df1 = df1[df1['col2'].isin(df2['col1'])]

如果需要直接修改原df1,可直接赋值覆盖:

df1 = df1[df1['col2'].isin(df2['col1'])]

处理后结果

执行上述代码后,目标DataFrame的内容如下:

col1col2col3
abcdef1ghijkl1mnopqr1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 06:30:49