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

基于另一DataFrame列子串筛选DataFrame列值及报错解决

解决方法

你遇到的TypeError: unhashable type: 'list'是因为pandas.Series.str.contains()方法需要传入正则表达式字符串,而非列表类型参数。要实现筛选df1中'id'包含df2任意'id'子串的记录,可按以下方式修改代码:

步骤1:构造正则匹配模式

将df2的'id'列值拼接成用|分隔的正则字符串,以此实现“匹配任意一个子串”的逻辑:

pattern = '|'.join(df2['id'].tolist())

针对你的示例数据,这会生成'123|456'的模式,代表匹配包含'123'或'456'的字符串。

步骤2:执行筛选

把构造好的模式传入str.contains()完成筛选:

filtered_df = df1[df1['id'].str.contains(pattern)]

完整代码示例

import pandas as pd

data = {
  'id': ['TEST-123','WORD-456', 'ABC-789']
}

data2 = {
  'id':['123','456']
}

df1 = pd.DataFrame(data)
df2 = pd.DataFrame(data2)

# 构造匹配模式
pattern = '|'.join(df2['id'].tolist())
# 筛选符合条件的记录
filtered_df = df1[df1['id'].str.contains(pattern)]
print(filtered_df)

运行后输出结果:

id
0  TEST-123
1  WORD-456

注意事项

如果df2的'id'中包含正则表达式特殊字符(如., *, ?等),需要先用re.escape()转义每个字符串,避免匹配逻辑出错:

import re
pattern = '|'.join(re.escape(s) for s in df2['id'].tolist())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 21:52:37