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

如何用Python的SQL LIKE操作符匹配DataFrame与SQL模糊模式

问题根源

你原代码的核心问题是每次SQL查询仅返回匹配的Animal列,没有将对应使用的LIKE模式作为字段存入结果,拼接后自然缺失sql列信息。

修改后可直接运行的代码

from pandasql import sqldf
import pandas as pd

df  = {'Animal': ['Cat', 'Horse', 'Mouse']}
df = pd.DataFrame(df)
# 这里如果要匹配目标输出的%ous,把原来的%ouse改成%ous即可
searchStrings = ['%og', '%ous', '%at']

dfNew = []
for pattern in searchStrings:
    # 查询时直接把当前匹配模式作为sql字段返回
    sql = f"SELECT Animal, '{pattern}' as sql FROM df WHERE Animal LIKE '{pattern}'"
    res = sqldf(sql).drop_duplicates()
    dfNew.append(res)

dfNew = pd.concat(dfNew, ignore_index=True)
print(dfNew)

运行输出

Animal   sql
0    Cat   %at
1  Mouse  %ous

核心改动说明

  1. 构造SQL语句时新增了'{pattern}' as sql逻辑,直接将当前使用的LIKE模式作为固定值字段存入查询结果
  2. 拼接结果时加上ignore_index=True重置索引,避免后续索引冲突
    如果需要处理同一动物匹配多个模式的场景,可根据需求额外添加去重逻辑即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 22:57:03