ag-gridconditional-formattingstreamlit

Streamlit conditional formatting for rows in a table


I'm trying to add conditional formatting to table rows in my streamlit app. Using streamlit-aggrid package for it, for now, I found a way to format the table only per-column, for example:

gb = GridOptionBuilder.from_dataframe(mydf)
jscode = JsCode("""
function(params) {
    if (params.value > 70) {
        return {
            'color': 'white'
            'backgroundColor': '#fa7e74'
        }
    } else {
        return {
            'color': 'black'
            'backgroundColor': '#cdf6df'
        }
    }
};
""")
gb.configure_columns(mydf.columns[col_list], cellStyle=jscode, editable=True)
gridOptions = gb.build()
AgGrid(mydf,gridOptions=gridOptions,allow_unsafe_jscode=True)

I want to get something like this: enter image description here


Solution

  • I found this article on medium how to make it with Seaborn:

    # Set CSS properties for th elements in dataframe
    th_props = [
            ('font-size', '15px'),
            ('text-align', 'center'),
            ('font-weight', 'bold'),
            ('color', '#6d6d6d'),
            ('backgroud-color', '#f7ffff')
            ]
    
    #Set table styles
    styles = [
            dict(selector="th", props=th_props)
            ]
    
    #Set colormap equal to seaborn light green color palette
    cm = sns.light_palette('green', as_cmap=True)
    
    
    table_to_render = (mydf.style
            .background_gradient(cmap=cm, axis=1)
            .set_caption('This is custom caption.')
            .format(na_rep = 'No data', precision=2, thousands=',')
            .highlight_null(null_color='white')
            .set_table_styles(styles))
    st.table(table_to_render)