Dash新冠数据仪表盘添加日期选择器后数据类型不识别报错如何解决
问题根源
两类报错的核心都是日期类型不匹配:
- 从Excel读取的
date列是字符串格式,未做类型转换,无法和datetime.date对象直接做比较,这是TypeError的直接诱因 - 日期转换操作冗余,且DatePickerRange未设置初始起止日期,首次加载时传入空值也可能触发格式转换报错
具体修改步骤
1. 加载数据后转换日期列格式
在保留目标字段的代码后新增类型转换逻辑,让DataFrame的date列和后续比较的对象类型对齐:
df.drop( df.columns.difference(['continent', 'location', 'date', 'total_cases', 'new_cases', 'total_deaths', 'new_deaths']), 1, inplace=True) # 新增:把date列转换为datetime.date类型 df['date'] = pd.to_datetime(df['date']).dt.date
2. 给DatePickerRange添加默认起止日期
避免初始加载时start_date、end_date为空触发异常:
dcc.DatePickerRange( id='my-date-picker-range', min_date_allowed=date(2020, 1, 1), max_date_allowed=date.today(), initial_visible_month=date(2020, 1, 1), # 新增默认起止日期 start_date=date(2020,1,1), end_date=date.today(), display_format='YYYY-MM-DD', ),
3. 简化回调内的日期转换逻辑,修复绘图数据引用错误
回调内不需要冗余的字符串转换,同时修正绘图时y值的数据源引用错误(原来取的是全量df的字段,会导致数据行数不匹配):
@app.callback(Output(component_id='bar_plot', component_property='figure'), [Input(component_id='dropdown', component_property='value'), Input('my-date-picker-range', 'start_date'), Input('my-date-picker-range', 'end_date') ]) def graph_update(dropdown_value, start_date, end_date): # to get the world subset since the dataset contains multiple locations worldwide_subset = df.loc[df['location'] == 'World'] if start_date is not None and end_date is not None: # 直接用fromisoformat转换,无需额外转字符串 start_date_object = date.fromisoformat(start_date) end_date_object = date.fromisoformat(end_date) mask = (df['date'] > start_date_object) & (df['date'] <= end_date_object) used_df = df.loc[mask] else: used_df = worldwide_subset # 这里y值原来用的是df,改为从筛选后的used_df取 fig = go.Figure([go.Scatter(x=used_df['date'], y=used_df[dropdown_value], line=dict(color='firebrick', width=4)) ]) fig.update_layout(title=dropdown_value + ' over time', xaxis_title='date', yaxis_title=dropdown_value ) return fig
修改完成后两类报错都会消失,日期筛选功能可正常运行。
内容的提问来源于stack exchange,提问作者Sithija Piyuman Thewa Hettige
相关产品推荐
相关产品推荐

