Datatable - Apply conditional formatting to all columns


#1

This should be very simple, but I am completely new to Dash, so I am not sure of the syntax yet.

I’m trying to use conditional style formatting on a datatable to make all negative numbers appear in red. Below is an example of what I want to do, but only done on one column. I would like to do this for all columns. Also the column headers (in this case years) might change over time, so I would like to avoid hard coding any column names.

import dash
import dash_table
import dash_html_components as html
import pandas as pd
import numpy as np
from datetime import date

app = dash.Dash(__name__)

sColNames = [str(x) for x in range(date.today().year-6, date.today().year+1)]
df =  pd.DataFrame(data = np.array([[1.5,0.0,-1.5]]*7).T, index=range(3), columns=sColNames) # Example dataframe

dtTest = dash_table.DataTable(
        id='TestTable',
        columns=[{"name": i, "id": i} for i in df.columns],
        data=df.to_dict("rows"),
        style_data_conditional=[
        {
            'if': {
                'column_id': '2015',
                'filter': '2015 < num(0.0)' # Here I would like the same condition applied to all collumns not just "2015"
            }, 'color': 'red',
        },],)
app.layout = html.Div(children=[dtTest])

if __name__ == '__main__':
    app.run_server(debug=True)

I looked at https://dash.plot.ly/datatable/style but couldn’t make the examples work in this case.

Any suggestions are much appreciated


#2

@dhove There’s currently no way to express this as a single style expression.

You could generate the condition for each column (no explicit column id dependency) and apply the result like so:

styles = [{
    'if': {
        'column_id': str(x),
        'filter': '{} < num(0.0)'.format(x)
    },
    'color': 'red',
} for x in range(date.today().year-6, date.today().year+1)]

dash_table.DataTable(..., style_data_conditional=styles)


#3

I think that is a neat solution, and it works perfectly! So that is great, many thanks :slight_smile:

Using format like this also seems nice and flexible. I’ll remember this for future formatting.