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

Python Pandas:将匹配文本设为红色并高亮行的实现问题

解决DataFrame中匹配文本标红与行高亮的问题

嘿,我来帮你搞定这个需求!你想要把df1里和df3匹配的字符串改成红色字体,同时高亮对应行对吧?其实Pandas默认的样式工具没办法直接修改单元格内部分文本的颜色,得借助HTML标签配合Styler来实现,下面是具体的实现步骤:

1. 先构建完整的DataFrame

首先把你提供的数据集转换成标准的Pandas DataFrame:

import pandas as pd

df1 = ['i like to shop at store a.', 'he likes to shop at the store b.', 'she is happy to shop at store c.', 'we want to shop at the store d.']
df2 = ['store a', 'store b', 'store c', 'store d']
df3 = ['like to', 'likes to shop', 'at store']

# 构建DataFrame
df = pd.DataFrame(list(zip(df1, df2)), columns=['Text', 'Store'])

2. 编写文本标红的函数

我们需要一个函数来遍历每个文本,把匹配df3的部分用红色HTML标签包裹:

def highlight_matching_text(text):
    # 遍历df3中的每个匹配模式
    for pattern in df3:
        # 替换匹配的文本为红色样式,可选加粗增强醒目度
        text = text.replace(pattern, f'<span style="color:red; font-weight:bold;">{pattern}</span>')
    return text

3. 编写行高亮的函数

接下来写一个函数,判断每行是否包含匹配项,如果有就给整行加上高亮背景:

def highlight_matching_rows(row):
    # 检查当前行的Text列是否包含df3中的任意模式
    has_match = any(pattern in row['Text'] for pattern in df3)
    # 返回行样式:匹配的行用浅黄色背景,否则无样式
    return ['background-color: #fff3cd' if has_match else '' for _ in row]

4. 应用样式并展示

最后把这两个函数应用到DataFrame的样式上:

# 组合样式:先高亮行,再处理文本颜色
styled_df = df.style.apply(highlight_matching_rows, axis=1)\
                   .format({'Text': highlight_matching_text})\
                   .set_properties(**{'text-align': 'left', 'width': '400px'})

# 在Jupyter Notebook中直接运行就能看到效果,或者导出为HTML文件在浏览器打开
styled_df.to_html('styled_result.html')

额外优化:精确匹配(可选)

如果你担心出现部分匹配的问题(比如like to误匹配likes to),可以用正则表达式实现精确匹配:

import re

def highlight_matching_text(text):
    for pattern in df3:
        # 使用单词边界确保精确匹配完整短语
        text = re.sub(rf'\b{re.escape(pattern)}\b', f'<span style="color:red;">{pattern}</span>', text)
    return text

这样处理后,匹配的文本会变成红色,包含匹配项的行也会有浅黄色高亮背景,完美实现你的需求!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:47:10