Python DashTable未在回调中使用DatePickerSingle输入更新
我是dash的新手,我已经尽可能多地阅读,以了解问题可能是什么。简而言之,我有一个datepicker,它是DataTable和Graph回调的输入。图形回调工作正常,因此引起问题的只是DataTable。我还尝试了从单输入到多输出的回调,但没有成功。我的代码如下:Python DashTable未在回调中使用DatePickerSingle输入更新,python,callback,datepicker,plotly-dash,Python,Callback,Datepicker,Plotly Dash,我是dash的新手,我已经尽可能多地阅读,以了解问题可能是什么。简而言之,我有一个datepicker,它是DataTable和Graph回调的输入。图形回调工作正常,因此引起问题的只是DataTable。我还尝试了从单输入到多输出的回调,但没有成功。我的代码如下: app = JupyterDash() folder = os.getcwd() portfolio_returns_table = pd.read_csv(Path(folder, 'portfolioreturns_maria
app = JupyterDash()
folder = os.getcwd()
portfolio_returns_table = pd.read_csv(Path(folder, 'portfolioreturns_maria.csv',parse_dates=[0]))
portfolio_returns_table = portfolio_returns_table.set_index('Unnamed: 0')
name_portfolioID_table = pd.read_csv(Path(folder, 'name_portfolioID.csv'))
#Calculate portfolio cumulative returns
df_cumret = (portfolio_returns_table+1).cumprod().round(5)
df_cumret.index = pd.to_datetime(df_cumret.index)
app.layout = html.Div(html.Div([dcc.DatePickerSingle(
id='my-date-picker-single',
min_date_allowed=dt.date(df_cumret.index.min()),
max_date_allowed=dt.date(df_cumret.index.max()),
initial_visible_month=dt.date(df_cumret.index.max()),
date = dt.date(df_cumret.index.max())
,display_format = 'Y-MM-DD',clearable = True),
html.Div(id='output-container-date-picker-single'),
html.Div(dash_table.DataTable(id = 'data_table',
data = {},
fixed_rows={'headers': True},
style_cell = {'textAlign': 'left'},
style_table={'height': 400})),
html.Div(dcc.Graph('my_graph'))
]))
@app.callback([Output('data_table','data'),Output('data_table','columns')],
[Input('my-date-picker-
single','date')])
def update_leader_table(date):
#Get data for the selected date and transpose
df_T = df_cumret.loc[[date]].T
#Sort the table to reveal the top leaders
df_Top = df_T.sort_values(df_T.columns[0], ascending=False)[:10]
#Convert the index to an interger
df_Top.index = df_Top.index.astype(int)
#Generate the leaderboard to given date
df_leader = pd.merge(df_Top,name_portfolioID_table,
left_index=True,right_index=True, how = 'left')
#Create the col rank
df_leader['Rank'] = range(1,len(df_leader)+1)
df_leader.columns = ['Cum Return', 'Investor','Rank']
df_leader.reset_index(drop = True, inplace = True)
data = df_leader.to_dict('records')
columns= [{'id': c, 'name': c, "selectable": True} for c in
df_leader.columns]
return (data,columns)
#callback to link calendar to graph
@app.callback(Output('my_graph','figure'),[Input('my-date-picker-single','date')])
def update_graph(date):
#date filter
df_T = df_cumret.loc[:date].T
#Sort the table to reveal the top leaders & filter for leaderboard
df_Top = df_T.sort_values(df_T.columns[-1], ascending=False)[:10]
#Transpose to have date as index
df_top_graph = df_Top.T
#set the columns as an Int
df_top_graph.columns = df_top_graph.columns.astype(int)
#Rename columns
df_top_graph.rename(columns=dict(zip(name_portfolioID_table.index,
name_portfolioID_table.name)),
inplace=True)
#Generate graph
fig = px.line(df_top_graph, x = df_top_graph.index, y =
df_top_graph.columns, title='ETF LEADERBOARD PERFORMANCE: '+date, labels=
{'Unnamed: 0':'Date','value':'Cumulative Returns'})
fig.update_layout(hovermode = 'x unified')
fig.update_traces(hovertemplate='Return: %{y} <br>Date: %{x}')
fig.update_layout(legend_title_text = 'Investor')
return fig
if __name__ == '__main__':
app.run_server(mode = 'inline',debug=True, port = 65398)
app=JupyterDash()
folder=os.getcwd()
公文包返回表=pd.read\u csv(路径(文件夹'portfolioreturns\u maria.csv',解析日期=[0]))
portfolio_returns_table=portfolio_returns_table.set_index('未命名:0')
name\u portfolioID\u table=pd.read\u csv(路径(文件夹,'name\u portfolioID.csv'))
#计算投资组合累积回报
df_cumret=(投资组合收益表+1).cumprod().round(5)
df_cumret.index=pd.to_datetime(df_cumret.index)
app.layout=html.Div(html.Div([dcc.DatePickerSingle(
id='my-date-picker-single',
min_date_allowed=dt.date(df_cumret.index.min()),
max_date_allowed=dt.date(df_cumret.index.max()),
初始可见月=日期(df_cumret.index.max()),
日期=日期(df_cumret.index.max())
,显示格式='Y-MM-DD',可清除=真),
html.Div(id='output-container-date-picker-single'),
html.Div(dash_table.DataTable(id='data_table',
数据={},
修复了_行={'headers':True},
style_单元格={'textAlign':'left'},
样式表={'height':400}),
Div(dcc.Graph('my_Graph'))
]))
@app.callback([Output('data_table','data')、Output('data_table','columns'))],
[输入('my-date-picker-
单个“,”日期“]))
def更新表格(日期):
#获取所选日期的数据并转置
df_T=df_cumret.loc[[日期]].T
#对表格进行排序,以显示最高领导人
df_Top=df_T.sort_值(df_T.列[0],升序=False)[:10]
#将索引转换为整数
df_Top.index=df_Top.index.astype(int)
#生成给定日期的排行榜
df_leader=pd.merge(df_Top,name_portfolioID_table,
左索引=真,右索引=真,如何=左)
#创建列组
df_前导['Rank']=范围(1,len(df_前导)+1)
df_leader.columns=[‘累计回报’、‘投资者’、‘排名’]
df_leader.reset_索引(drop=True,inplace=True)
数据=df_leader.to_dict('记录')
columns=[{'id':c,'name':c,“可选的”:True}用于中的c
df_leader.columns]
返回(数据、列)
#回调以将日历链接到图表
@应用程序回调(输出('my_graph','figure'),[Input('my-date-picker-single','date'))
def更新图表(日期):
#日期过滤器
df_T=df_cumret.loc[:date].T
#对表格进行排序以显示排行榜的前几名和筛选
df_Top=df_T.sort_值(df_T.列[-1],升序=False)[:10]
#将日期转换为索引
df_top_graph=df_top.T
#将列设置为Int
df_top_graph.columns=df_top_graph.columns.astype(int)
#重命名列
df_top_graph.rename(columns=dict(zip)(name_portfolioID_table.index,
name_portfolioID_table.name)),
原地=真)
#生成图形
图=px.线(df_top_图形,x=df_top_图形索引,y=
df_top_graph.columns,title='ETF排行榜绩效:'+日期,标签=
{'Unnamed:0':'Date','value':'Cumulative Returns'})
图更新_布局(hovermode='x unified')
图更新跟踪(hovertemplate='Return:%%{y}
日期:%%{x}')
图更新布局图(图例标题文本='Investor')
返回图
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
app.run_服务器(模式='inline',调试=True,端口=65398)
欢迎来到SO!请您修改代码块的格式(请咨询)。正如您所看到的,缩进不合适,还有其他错误。我试图修复它,但丢失了,没有时间去做。@Timus谢谢你的反馈,我现在已经正确缩进了代码,希望它看起来更好,谢谢你的时间。嘿,你的代码有点长,并且使用了其他人没有的数据,所以其他人很难调试你的代码。我建议尝试创建一个最小的工作示例,有人可以复制、粘贴并自己尝试。您可以逐渐删除部分代码,直到只有一个小的布局框架和一个针对数据
和列
属性的回调,使用带有虚拟数据的数据帧。而且,当你到达那里的时候,你很可能已经发现了你的bug!感谢@nedned的反馈,我最终找到了bug,它没有将日期选择器中的日期转换为回调中的日期时间对象。我不知道日期是作为字符串传递的。