Changing the color of a specific keyword inside a pandas dataframe

Hi, I was wondering if there is any way to change a specific keyword inside a cell. Here is a code that I’ve written that changes the whole content of the cell that I want -

import streamlit as st
import pandas as pd
def main():
    # Sample data
    data = {
        'Title': ['Article 1', 'Article 2', 'Article 3'],
        'Content': [
            'The stock market experienced a downturn today.',
            'The housing market is booming.',
            'Investors are uncertain about the future of the company.'
        ]
    }
    df = pd.DataFrame(data)
    st.title('Table with Highlighted Term')
    # Display the table with highlighting
    st.dataframe(df.style.applymap(lambda x: 'color: red' if any('market' in words for words in x.split()) else ''))
if __name__ == '__main__':
    main()

Here I am changing the font color of the Content column in which the term “market” is present.

Is there any way to change only the term market from the cells?

1 Like

Hi @Vansh_Sharma,

Thanks for posting!

A quick hack is to use regex to find the instances of market or Marketin the cells underContent` column then apply the red color to the instances.

Finally, you display the dataframe using st.markdown with unsafe_allow_html=True` to allow the rendering of the HTML tags.

See the updated code below and the demo app as well.

import streamlit as st
import pandas as pd
import re

def main():
    # Sample data
    data = {
        'Title': ['Article 1', 'Article 2', 'Article 3', 'Article 4'],
        'Content': [
            'The stock market experienced a downturn today.',
            'The housing market is booming.',
            'Investors are uncertain about the future of the company.',
            'The tech Market is thriving amidst the pandemic.'
        ]
    }
    df = pd.DataFrame(data)
    st.title('Table with Highlighted Term')
    # Display the table with highlighting
    def highlight_market(cell):
        def repl(match):
            return '<span style="color: red;">{}</span>'.format(match.group())
        cell = re.sub(r'market', repl, cell, flags=re.I)
        return cell
    df['Content'] = df['Content'].apply(highlight_market)
    st.markdown(df.to_html(escape=False), unsafe_allow_html=True)

if __name__ == '__main__':
    main()
2 Likes

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.