Python Plotly分组柱状图过滤周末计算日度差值报错排查
问题根因
- 对pandas DataFrame做布尔条件过滤后,原始行索引会被保留,不会自动重置为从0开始的连续整数。样例数据过滤掉周末行后,剩余行的索引为
0和3,但原差值计算逻辑用while循环从0开始按连续整数取y1[i]、y2[i],当i取到1时,会因为找不到对应索引值触发KeyError。 - 原写法还存在隐性bug:如果两个DataFrame过滤后日期顺序、数量不一致,手动按位置遍历计算的差值会和日期错位,标注结果错误。
快速修复代码
只需要在过滤后重置索引,同时用pandas原生向量运算代替手动while循环计算差值,从写法上避免索引遍历错误:
import plotly.graph_objects as go import pandas as pd df1 = pd.DataFrame({ 'score': [11,42,31,22], 'dates': ['7/1/2022','7/2/2022','7/3/2022','7/4/2022'], 'weekend': [0,1,1,0], }) df2 = pd.DataFrame({ 'score': [44,45,26,22], 'dates': ['7/1/2022','7/2/2022','7/3/2022','7/4/2022'], 'weekend': [0,1,1,0], }) # 过滤周末数据后重置索引,丢弃原索引 df1 = df1[df1['weekend'] == 0].reset_index(drop=True) df2 = df2[df2['weekend'] == 0].reset_index(drop=True) y1 = df1['score'] y2 = df2['score'] # 直接做向量运算计算差值,无需手动写循环 c = (y1 - y2).astype(str).tolist() fig = go.Figure(data=[ go.Bar(name='SF Zoo', x=df1['dates'], y=y1), go.Bar(name='LA Zoo', x=df2['dates'], y=y2, text=c, textposition='outside') ]) fig.update_layout(barmode='group') fig.show()
更稳健的优化写法
为了避免两个表分别过滤可能出现的日期不匹配、错位问题,可以先按日期合并两个数据集,再统一做过滤、差值计算,适配更复杂的真实数据场景:
import plotly.graph_objects as go import pandas as pd df1 = pd.DataFrame({ 'score': [11,42,31,22], 'dates': ['7/1/2022','7/2/2022','7/3/2022','7/4/2022'], 'weekend': [0,1,1,0], }) df2 = pd.DataFrame({ 'score': [44,45,26,22], 'dates': ['7/1/2022','7/2/2022','7/3/2022','7/4/2022'], 'weekend': [0,1,1,0], }) # 按日期关联合并两个数据源的得分 merged_df = pd.merge( df1[['dates', 'score', 'weekend']].rename(columns={'score':'sf_score'}), df2[['dates', 'score']].rename(columns={'score':'la_score'}), on='dates', how='inner' ) # 统一过滤周末数据 merged_df = merged_df[merged_df['weekend'] == 0] # 计算两组得分差值 merged_df['diff'] = (merged_df['sf_score'] - merged_df['la_score']).astype(str) fig = go.Figure(data=[ go.Bar(name='SF Zoo', x=merged_df['dates'], y=merged_df['sf_score']), go.Bar(name='LA Zoo', x=merged_df['dates'], y=merged_df['la_score'], text=merged_df['diff'], textposition='outside') ]) fig.update_layout(barmode='group') fig.show()
内容的提问来源于stack exchange,提问作者tenebris silentio
相关产品推荐
相关产品推荐

