Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Pandas: Highlight matching text and row

Tags:

python

pandas

I’m trying to change the font color to red for any strings in df1 that match values in df3 and highlight the row. I couldn't find any information about changing font color. The data sets are:

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’ ]

I'm using the following:

myDataSet = list(zip(df1,df2))
df = pd.DataFrame(data = myDataSet, columns=[‘df1’, ‘df2’]

The output should look like:

enter image description here

Please help!

like image 287
Steve DEU Avatar asked Jul 25 '26 12:07

Steve DEU


1 Answers

It is accomplishable inside a Jupyter Notebook using HTML formatting, as @Ywapom suggested. Please check his answer as well.

import re
from IPython.display import HTML

def display_highlighted_words(df, keywords):
    head = """
    <table>
        <thead>
            """ + \
            "".join(["<th> %s </th>" % c for c in df.columns])\
            + """
        </thead>
    <tbody>"""

    for i,r in df.iterrows():
        row = "<tr>"
        for c in df.columns:
            matches = []
            for k in keywords:
                for match in re.finditer(k, str(r[c])):
                    matches.append(match)
        
            # reverse sorting
            matches = sorted(matches, key = lambda x: x.start(), reverse=True)
        
            # building HTML row
            cell = str(r[c])
            for match in matches:
                cell = cell[:match.start()] +\
                    "<span style='color:red;'> %s </span>" % cell[match.start():match.end()] +\
                    cell[match.end():]
            row += "<td> %s </td>" % cell
                
            row += "</tr>"
        head += row

    head += "</tbody></table>"
    display(HTML(head))

Then, with tan example DataFrame like this one

df = pd.DataFrame([["Franco color Franco",1], 
                   ["Franco Franco Ciccio Franco",2], 
                   ["Ciccio span",3]], columns=["A", "B"])
display_highlighted_words(df, ["Franco", "Ciccio"])

the result is the following.

Sample result

The above code could be easily extended to have the keywords vector to be selected from a column of the dataset, as the original question was asking.

like image 183
Matt07 Avatar answered Jul 27 '26 00:07

Matt07



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!