I am using streamlit with aggrid. I want color the cell based on the value. I am using pandas “apply” to apply color to each value but its not taking effect. It showing as html in the cell.
Here is my code.
ef apply_rss_label_color(value):
"""Apply color formatting to rss_label columns."""
# Ensure that the value is a string and handle NaN by replacing with empty string
value = str(value) if pd.notna(value) else ''
# Apply styles based on value
if "RW(Strong)" in value:
return f'<span style="color: red; font-weight: bold;">{value}</span>'
elif "RW(Slight)" in value:
return f'<span style="color: lightcoral; font-weight: bold;">{value}</span>'
elif "RW(Moderate)" in value:
return f'<span style="color: darkred; font-weight: bold;">{value}</span>'
elif "RS(Slight)" in value:
return f'<span style="color: #98FB98; font-weight: bold;">{value}</span>'
elif "RS(Moderate)" in value:
return f'<span style="color: limegreen; font-weight: bold;">{value}</span>'
elif "RS(Strong)" in value:
return f'<span style="color: green; font-weight: bold;">{value}</span>'
else:
return value # Return value as is if no match
###Main function snippet.
# Use Ag-Grid to display the table with the first row and column frozen
grid_options = GridOptionsBuilder.from_dataframe(filtered_data)
grid_options.configure_pagination(enabled=True) # Enable pagination
grid_options.configure_column('ticker', pinned='left') # Freeze the first column
grid_options.configure_column('rrs_label_2025-03-24', pinned='top') # Freeze the first row
# Apply color formatting to 'rss_label' columns using pandas.apply
for column in filtered_data.columns:
if 'rrs_label' in column:
filtered_data[column] = filtered_data[column].apply(apply_rss_label_color)
grid_options = grid_options.build()
# Display the table using Ag-Grid
AgGrid(filtered_data, gridOptions=grid_options, enable_enterprise_modules=True)
I have also tried using aggrid formatting it seems its not supported by streamlit. ‘get_rss_label_style’ is the method that gets the style to apply. The styling is not at all applied.
# Apply color formatting to 'rss_label' columns
for column in filtered_data.columns:
if 'rrs_label' in column:
grid_options.configure_column(column,
cellStyle=lambda params: get_rss_label_style(params.value)) # Use the get_rss_label_style function for cellStyle