破折号数据表条件单元格格式不起作用

Dash dataTable conditional cell formatting isn't working

我想change a color of a cell of a Dash dataTable 基于一个值。我尝试了一个最小的例子:

            html.Div(
            children=[
                dash_table.DataTable(
                    id='table_1',
                    data=df.to_dict('records'),
                    columns=[{"name": i, "id": i} for i in df.columns],
                    #conditional cell formating
                    style_data_conditional=[
                        {
                            'if': {
                                'column_id': 'col1',
                                'filter': 'col1 > num(15)'
                            },
                            'backgroundColor': '#3D9970',
                            'color': 'white',
                        },
                    ],
                    n_fixed_rows=2,
                    filtering=True,
                    sorting=True,
                    sorting_type="multi"
                )],
        )

添加 style_conditional 后,table 根本不显示,也没有抛出任何错误消息。 table 嵌入在 html 组件中,在查看论坛和 github 之后,我仍然不确定我是否遗漏了任何内容,以及是否需要为这个。上述 tutorial 中提供的示例并未暗示需要回调。

更新:

尝试 运行 具有相同代码和不同数据的最小版本,结果相同,即单元格颜色没有变化。我的库是最新的,但环境中的某些东西可能仍然会导致问题。

完整代码:

import dash
import dash_table
import pandas as pd

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/solar.csv')

# Having trouble with conditional when column name has spaces
df = df.rename({'Number of Solar Plants': 'Plants'}, axis='columns')
app = dash.Dash(__name__)

app.layout = dash_table.DataTable(
    id='table',
    columns=[{"name": i, "id": i} for i in df.columns],
    style_data_conditional=[{
        "if": {'column_id': 'State',
               'filter': 'State eq "Nevada"'
               },
        "backgroundColor": "#3D9970",
        "color": "white"
    }],
    data=df.to_dict('records'),
)

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

我认为您不需要像教程中所说的那样为此回调。根据本教程的最后一个例子,我认为你有一个错字(一个'到很多)。

更改此行

'filter': 'col1' > num(15)' 

至:

'filter': 'col1 > num(15)'

我有同样的问题,我发现直接给出索引而不是条件要容易得多。

style_data_conditional = [{'if': {'column_id': 'col1',"row_index": x},'backgroundColor': '#3D9970','color': 'white'} for x in df[df['col1']>15].index ]

它很难看,因为它是硬编码的,但当直接过滤器没有时,它对我有用。

我不知道 2019 年的情况如何,但最近发布了 Dash Datatables:

  1. 过滤器表达式中的列名必须用花括号括起来
  2. filter 已重命名为 filter_query
style_data_conditional=[{
    "if": {
        'column_id': 'State',
        'filter_query': '{State} eq "Nevada"'
        #                ^     ^ <-- required braces
    },
    "backgroundColor": "#3D9970",
    "color": "white"
}]

顺便说一句:您可以通过删除 column_id 行方便地突出显示整行。

如果您有兴趣,Dash 向 DataTable 条件格式添加了一些功能,因此我制作了一个教程来帮助其他人了解所有功能和格式语法。

https://youtu.be/S8ZcErBpfYE