How I can color a st.data_editor cell based on a condition

Hello,
I have this dataframe :

import streamlit as st
import pandas as pd

df = pd.DataFrame(
    [
       {"command": "test 1", "rating": 4, "is_widget": True},
       {"command": "test 2", "rating": 5, "is_widget": False},
       {"command": "test 3", "rating": 3, "is_widget": True},
   ]
)
edited_df = st.data_editor(df)

is there a way please to color a pecific cell based on a condition, I want to colorize in yellow the cell (in the rating col) when the value <2.

thanks for your help

I couldn’t find a way to do it for a cell so I did it for the row. Here is how you can do it. You will create a function and call that function in the style property for the df.

def highlight_rows(x):
    
    Columns_Num = 3

    if x.rating == 2:
        return['background-color: lightyellow']*Columns_Num
    if x.rating == 3:
        return['background-color: lightblue']*Columns_Num
    if x.rating >= 4 :
        return['background-color: lightgreen']*Columns_Num

Then apply the style to the df

df  = st.data_editor(df.style.apply(highlight_rows, axis = 1)

Try this:

def highlight(value,threshold):
     return "background-color: yellow;" if value<threshold else None 

styled_df=df.style.applymap(highlight,threshold=4,subset=["rating"])
edited_df = st.data_editor(styled_df)

Highlighting (and styling in general) is performed using Pandas’ styler. You define a function that returns the CSS to apply and use either applymap to apply it to individual cells, or apply to apply it to rows, columns or the entire table.

From the docs:

Pass your style functions into one of the following methods:

  • Styler.applymap: elementwise
  • Styler.apply: column-/row-/table-wise

You can use the subset parameter to apply the style to only specific rows or columns. This is explained in Finer Control: Slicing :

Both Styler.apply , and Styler.applymap accept a subset keyword. This allows you to apply styles to specific rows or columns, without having to code that logic into your style function.

Any extra named properties are passed to your function as parameters. I added threshold so I could experiment a bit.

There are shortcut methods that can apply built-in styles directly. For example, you can use background_gradient to apply a gradient to the ratings column with :

styled_df=df.style.background_gradient(cmap="YlGnBu",subset=["rating"])