我想根据下拉列表中的回调选择,在我的短划线布局中显示div内某些条件的计数。
我能够获得pandas dataframe列中值的下拉列表,但是我无法确定如何显示列中所选元素的总数。
例如,我在Jupyter笔记本中编写了一个函数来计算
def getCount(df, selected_org):
totCount = df[df['ORGANIZATIONS'] == selected_org].AGENCY.count()
return count
selected_org = 'REGION 1'
getCount(df, selected_org)
其中显示的值为:3187
该值是我的selected_org变量的结果。
现在,我想根据下拉列表中的选择在我的仪表板布局中做同样的事情。我在这里使用了很多代码来开始Udemy课程:带有Plotly和Dash的交互式Python仪表板
我从我的布局开始:
org_options = []
for org in df['ORG_CODE_LEVEL_2_SHORT'].unique():
org_options.append({'label': str(org), 'value': org})
app.layout = html.Div(children=[
html.Label('Select Org:'),
dcc.Dropdown(id='org-dropdown', options=org_options,
value=df['ORG_CODE_LEVEL_2_SHORT'].min()),
html.P(html.Div(id='container'))
然后我回电话:
@app.callback(
Output(component_id='container', component_property='children'),
[Input(component_id='org-dropdown', component_property='value')])
def update_table(selected_org):
filtered_org = df[df['ORG_CODE_LEVEL_2_SHORT'] == selected_org]
return getCount(df, filtered_org)
以及生成计数的函数:
def getCount(df, selected_org):
totCount = df[df['ORG_CODE_LEVEL_2_SHORT'] ==
selected_org].AGENCY_INFO_5.count()
return html.H2(totCount)
哪个给我以下内容:
但它没有给我数数。任何帮助表示赞赏。
最终完成计划:
import os
import glob
import pandas as pd
import numpy as np
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
app = dash.Dash()
# DATA FROM EEPROFILE
path = r'mydata'
extension = 'xlsx'
os.chdir(path)
files = [i for i in glob.glob('*.{}'.format(extension))]
latest_file = max(files, key=os.path.getctime)
df = pd.DataFrame()
eeprofi = pd.read_excel(latest_file, converters={'ORG_CODE_LEVEL_3': str})
df = df.append(eeprofi)
def getCount(df, selected_org):
totCount = df[df['ORG_CODE_LEVEL_2_SHORT'] == selected_org].AGENCY_INFO_5.count()
return html.H2(totCount)
org_options = []
for org in df['ORG_CODE_LEVEL_2_SHORT'].unique():
org_options.append({'label': str(org), 'value': org})
app.layout = html.Div(children=[
html.Label('Select Org:'),
dcc.Dropdown(id='org-dropdown', options=org_options, value=df['ORG_CODE_LEVEL_2_SHORT'].min()),
html.P(html.Div(id='container'))
])
@app.callback(
Output(component_id='container', component_property='children'), [Input(component_id='org-dropdown', component_property='value')])
def update_table(selected_org):
filtered_org = df[df['ORG_CODE_LEVEL_2_SHORT'] == selected_org]
return getCount(df, filtered_org)
if __name__ == '__main__':
app.run_server()
你的输入是一个孩子,所以你应该返回一个列表,而不是像你那样返回html.H2(your_count);)所以解决方案就是替换这个函数
def getCount(df, selected_org):
totCount = df[df['ORG_CODE_LEVEL_2_SHORT'] == selected_org].AGENCY_INFO_5.count()
return html.H2(totCount)
通过这个:
def getCount(df, selected_org):
totCount = df[df['ORG_CODE_LEVEL_2_SHORT'] == selected_org].AGENCY_INFO_5.count()
return [html.H2(totCount)]