0
votes

I've got the following code:

import dash
import dash_html_components as html
import dash_table
import pandas as pd

df = pd.DataFrame(
    columns = ['col1', 'col2'],
    data=[
        ['aaaa', 5],
        ['aa', 6],
        ['bbbb', 7],
        ['cccc',8]

    ]

)
app = dash.Dash(__name__)

styles = [{'if': {
                        'column_id': 'col1',
                        'filter_query': '{col1} contains {val}'
                    },
                    'backgroundColor': background_color,
                    'color': 'white'
                } for val, background_color in zip(['a', 'b', 'c'], 
                            ['#FF0000', "#00FF00", '#0000FF'])]

app.layout = html.Div([dash_table.DataTable(
        id='table',
        columns=[{"name": i, "id": i} for i in df.columns],
        data=df.to_dict('records'),
        style_cell={'font-family':'sans-serif'},
        style_data_conditional=styles
)])


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

I'm trying to change the background color of the col1 column if it contains a, b or c. I know that I need to use style_data_conditional, but can't figure out how to reference the column name correctly. Does anyone know how?

1

1 Answers

1
votes

The problem with the filter query in your code is that val is a string and is therefore not being updated based on the values in the list (i.e. it is always equal to 'val' instead of taking the values 'a', 'b' and 'c'). If you replace val with a variable as in the example below your code should work as expected.

import dash
import dash_html_components as html
import dash_table
import pandas as pd

df = pd.DataFrame(
    columns=['col1', 'col2'],
    data=[['aaaa', 5],
          ['aa',   6],
          ['bbbb', 7],
          ['cccc', 8]]
)

app = dash.Dash(__name__)

styles = [{'if': {'column_id': 'col1', 'filter_query': '{col1} contains ' + val},
'backgroundColor': background_color, 'color': 'white'} for val, background_color
in zip(['a', 'b', 'c'], ['#FF0000', "#00FF00", '#0000FF'])]

app.layout = html.Div([dash_table.DataTable(
        id='table',
        columns=[{'name': i, 'id': i} for i in df.columns],
        data=df.to_dict('records'),
        style_cell={'font-family': 'sans-serif'},
        style_data_conditional=styles
)])

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

enter image description here