I am using Dash to display a DataTable. In certain column, each cell contains a string (a long string of comma-separated values). I am looking for a way to format a color (e.g. change it to red) of just some values in the cells based on matching with elements in the list "l". So if there is a value in the list, I would like to have it red in the Dash DataTable but a rest of the string in the cell I need in default color. I guess, there will be a way through a regex expression like in this example: DataTable - Color only substring in a cell I also tried to use "style_data_conditional" with "filter_query" which colored all the string in cell. This is my testing copy for string "a":
style_data_conditional = [
{'if': {'filter_query': '{col1} contains "a"',
'column_id':'col1'},
'color': 'tomato',
'fontWeight': 'bold',
},
Can you guys help me on this? Edited: another challenge is to implement a callback and return this "new style", too. Thanks.
import pandas as pd
import numpy as np
import dash
from dash import Dash, html, dcc, dash_table
from dash.dash_table.Format import Format, Sign
from dash.dependencies import Input, Output, State
from dash import dash_table
df = pd.DataFrame({
"col1":["a, b, c, d", "a, b, d", "a, b, z, x, y", "a, y","y, z, b"],
"col2":[0, 1, 0, 1, 2]})
l = ["a", "b", "c"]
result_table = dash_table.DataTable(
id = 'df',
data = df.to_dict('records'),
columns = [{'name': str(i), 'id': str(i)} for i in df.columns]
)
external_stylesheets = ["https://codepen.io/chriddyp/pen/bWLwgP.css"]
app = Dash(__name__, external_stylesheets = external_stylesheets)
app.layout = html.Div([
html.Div([result_table]),
])
if __name__ == '__main__':
app.run_server(debug = True, port = 8010)
Update: I think it could be possible to color certain sub-string using (like in the example linked above)
substituted = pattern.sub(
f"<span style='color: {color};'>{found.group()}</span>", value)
However, I am not quite sure how to "get the styling to the Dash app. through its @app.callback
". Would that be possible to update the DataTable with "colored data" using standard data.to_dict('records')
?
Thank you.