Plotly-Dash如何用同一下拉组件匹配Investor、Fund列过滤仪表盘
实现方案
不需要复杂的groupby逻辑,分两步调整即可实现单下拉框同时筛选投资者、基金的功能:
- 合并两类字段的唯一值生成下拉选项,给每个选项加类型标识避免重名冲突、区分选项类型
- 回调中拆分选中值,分别匹配投资者、基金列后合并过滤结果
具体代码修改
1. 替换下拉选项配置
将原有仅生成投资者选项的代码,替换为同时生成两类选项的逻辑,明确区分投资者、基金选项,避免用户混淆:
# 原代码: # options=[{'label': i, 'value': i} for i in df['Investor'].unique()] # 替换为: investor_options = [ {"label": f"[投资者] {name}", "value": f"investor:{name}"} for name in df["Investor"].unique() ] fund_options = [ {"label": f"[基金] {name}", "value": f"fund:{name}"} for name in df["Fund"].unique() ] # 合并后传入下拉组件 options=investor_options + fund_options
2. 调整回调过滤逻辑
原有逻辑仅匹配Investor列,需要改为同时匹配Investor、Fund两列,任意一列符合选中条件即保留数据行:
# 原代码: # def display_table(dropdown_value): # if dropdown_value is None: # return generate_table(df) # dff = df[df.Investor.str.contains('|'.join(dropdown_value))] # dff = dff[['Investor', 'Period Date', 'Symbol','Shares', 'Value']] # return generate_table(dff) # 替换为: def display_table(dropdown_value): if dropdown_value is None: return generate_table(df) # 拆分选中项为投资者、基金两个列表 selected_investors = [] selected_funds = [] for val in dropdown_value: if val.startswith("investor:"): selected_investors.append(val.split(":", 1)[1]) elif val.startswith("fund:"): selected_funds.append(val.split(":", 1)[1]) # 两类条件取或合并过滤结果 dff = df[ df["Investor"].isin(selected_investors) | df["Fund"].isin(selected_funds) ] # 保留Fund列方便用户核对筛选结果 dff = dff[["Investor", "Fund", "Period Date", "Symbol", "Shares", "Value"]] return generate_table(dff)
完整可运行代码
import dash import dash_core_components as dcc import dash_html_components as html import pandas as pd data = {'Investor': {0: 'Rick', 1: 'Faye', 2: 'Rick', 3: 'Dre', 4: 'Faye', 5: 'Mike', 6: 'Mike', 7: 'Mike'}, 'Fund': {0: 'Fund 3', 1: 'Fund 2', 2: 'Fund 3', 3: 'Fund 4', 4: 'Fund 2', 5: 'Fund 1', 6: 'Fund 1', 7: 'Fund 1'}, 'Period Date': {0: '2019-06-30', 1: '2015-03-31', 2: '2018-12-31', 3: '2020-06-30', 4: '2015-03-31', 5: '2015-03-31', 6: '2018-12-31', 7: '2018-12-31'}, 'Symbol': {0: 'AVLR', 1: 'MEG', 2: 'BAC', 3: 'PLOW', 4: 'DNOW', 5: 'JNJ', 6: 'QSR', 7: 'LBTYA'}, 'Shares': {0: 3, 1: 11, 2: 10, 3: 2, 4: 10, 5: 1, 6: 4, 7: 3}, 'Value': {0: 9, 1: 80, 2: 200, 3: 10, 4: 100, 5: 10, 6: 20, 7: 12}} df = pd.DataFrame.from_dict(data) def generate_table(dataframe, max_rows=100): return html.Table( [html.Tr([html.Th(col) for col in dataframe.columns])] + [html.Tr([ html.Td(dataframe.iloc[i][col]) for col in dataframe.columns ]) for i in range(min(len(dataframe), max_rows))] ) app = dash.Dash() # 提前生成两类下拉选项 investor_options = [ {"label": f"[投资者] {name}", "value": f"investor:{name}"} for name in df["Investor"].unique() ] fund_options = [ {"label": f"[基金] {name}", "value": f"fund:{name}"} for name in df["Fund"].unique() ] app.layout = html.Div( children=[ html.H4(children='Investor Portfolio'), dcc.Dropdown( id='dropdown', options=investor_options + fund_options, multi=True, placeholder='可同时选择投资者、基金进行筛选...' ), html.Div(id='table-container') ] ) @app.callback( dash.dependencies.Output('table-container', 'children'), [dash.dependencies.Input('dropdown', 'value')] ) def display_table(dropdown_value): if dropdown_value is None: return generate_table(df) selected_investors = [] selected_funds = [] for val in dropdown_value: if val.startswith("investor:"): selected_investors.append(val.split(":", 1)[1]) elif val.startswith("fund:"): selected_funds.append(val.split(":", 1)[1]) dff = df[ df["Investor"].isin(selected_investors) | df["Fund"].isin(selected_funds) ] dff = dff[["Investor", "Fund", "Period Date", "Symbol", "Shares", "Value"]] return generate_table(dff) if __name__ == '__main__': app.run_server(debug=True)
效果说明:用户选中任意数量的投资者、基金选项后,表格会自动返回所有满足「属于选中投资者 或 属于选中基金」的数据行,无需分设两个独立下拉框。
内容的提问来源于stack exchange,提问作者user53526356
相关产品推荐
相关产品推荐

