使用回调函数在仪表板表格中设置两个过滤器

2024-10-02 16:24:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我想根据所选日期过滤器或下拉列表或两者来筛选表。但是我无法集成这两个组件来与表交互。有人知道我哪里出错了吗

我不知道如何在一张桌子上放置两个过滤器

app.layout = html.Div([
    
    # Title
    html.Div([
        html.H1(children="test", id="title")
    ]),

    # Range Date
    html.Div(
        id="container_range_date",
        children=dcc.DatePickerRange(
            id="date_range",
            min_date_allowed=date(2016, 1 , 1),
            max_date_allowed=date(2021, 12, 31),
            initial_visible_month=date(2016, 1, 1),
            start_date=date(2026, 1, 1),
            end_date=date(2021, 12, 31)
        )
    ),

    # Menu Dropdown
    html.Div(
        id="container_col_select",
        children=dcc.Dropdown(
            id="col_select",
            options=[{"label":i, "value":i} for i in df["customer"].unique()],
            value=df["customer"][0:].unique(),
            multi=True,
            placeholder="customer"
        )
    ),    

    # Data Table
    dash_table.DataTable(
        id="table",
        columns=[{"name":x, "id":x} for x in df.columns],
        data=df.to_dict("rows"),
        fixed_rows={'headers':True},
        export_format="xlsx",
        filter_action="native"
    )
])

# Callback
@app.callback(
    Output("table", "data"),
    [Input("col_select", "value"),
    Input("date_range", "start_date"),
    Input("date_range", "end_date")]
)
def outputUpdate(dropdownValue, startDate, endDate):
    if type(dropdownValue) != str:
        dfFiltered = df[(df["customer"].isin(dropdownValue)) & (df["date"] >= startDate) & (df["date"] <= endDate)]
    else:
        dfFiltered = df[df["customer"] == dropdownValue]
    return dfFiltered.to_dict("rows")

Tags: dividdfinputdatevaluehtmltable
1条回答
网友
1楼 · 发布于 2024-10-02 16:24:53

请随意使用此示例并根据您的数据模型进行调整:

@app.callback(
    Output('table-container', 'data'),
    [Input('Filter1_dropwdown', 'value'),
     Input('Filter2_dropwdown', 'value')]
    )

def filter_df(filter_01, filter_02):
    if (not filter_01 and not filter_02):
        # Return all the rows on initial load
        return df.to_dict('records')


    filtered = df.query('filter_1_field in @filter_01 or filter_2_field in @filter_02')
    return filtered.to_dict('records')

相关问题 更多 >