DataTable - 单元格中的唯一颜色子字符串

DataTable - Color only substring in a cell

我想知道是否可以只对 DataTable 单元格的部分文本应用颜色

目前我有这个 table:

那个table的代码是这个:

DataTable(
            id="comparison_table",
            columns=[{"name": "Version", "id": "Version"},
                     {"name": "Nº entities", "id": "Nº entities"},
                      {"name": "Nº types", "id": "Nº types"}
                      ],
            style_header=
           {
              'fontWeight': 'bold',
              'font-size': '1.1067708333333333vw',
              'text-align': 'center'
           },
           style_cell={'text-align': 'left'},
            data=[
        {
            "Version": value1,
            "Nº entities": entities_version1,
            "Nº types": types_version1
        },
        {
            "Version": value2,
            "Nº entities": entities_version2 + entity_growth_text ,
            "Nº types": types_version2 + type_growth_text
        }
        ],
            fill_width=False,
            style_table={
                'overflowY': 'scroll', 'height': '8.138020833333334vw', 'width': '97.65625vw', 'margin-left': '0.6510416666666666vw'
                         }
        )
                ]
                )

我只想给 table 第二行的括号上色。在这种情况下,entity_growth_texttype_growth_text 变量。

如果括号内的数字以+开头,颜色应该是green

否则,如果括号内的数字以 - 开头,颜色应为 red

希望你能帮我解决这个问题。提前致谢。

您可以利用最近添加的功能,该功能允许在降价单元格 (source) 中使用 html:

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

df = pd.DataFrame(
    {
        "Version": ["Oct 1st 2016", "June 1st 2021"],
        "Nº entities": ["5765325", "7435957 (+1670632)"],
        "Nº types": ["418", "421 (-3)"],
    }
)

pattern = re.compile("(\(.*?)\)")


def color_brackets(value):
    found = re.search(pattern, value)

    if found:
        color = "red"

        if found.group()[1] == "+":
            color = "green"

        substituted = pattern.sub(
            f"<span style='background-color: {color};'>{found.group()}</span>", value
        )
        return substituted

    return value


df["Nº entities"] = df["Nº entities"].apply(color_brackets)
df["Nº types"] = df["Nº types"].apply(color_brackets)


app = dash.Dash(__name__)

app.layout = html.Div(
    [
        dash_table.DataTable(
            css=[dict(selector="p", rule="margin: 0px; text-align: center")],
            style_cell={"textAlign": "center"},
            data=df.to_dict("records"),
            columns=[
                {"name": "Version", "id": "Version"},
                {
                    "name": "Nº entities",
                    "id": "Nº entities",
                    "presentation": "markdown",
                },
                {"name": "Nº types", "id": "Nº types", "presentation": "markdown"},
            ],
            markdown_options={"html": True},
        )
    ]
)

if __name__ == "__main__":
    app.run_server()

所以上面的方法是创建一个正则表达式来匹配括号和里面的内容,这样我们就可以用我们可以设置样式的 html 元素包围这个表达式。

结果: