You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何处理Python+Streamlit中空DataFrame的查询与可视化报错

处理空DataFrame的报错问题

核心解决思路

先判断过滤得到的CurrentBOM是否为空,再分情况处理可视化逻辑:DataFrame不为空时正常展示,为空时显示友好提示,避免触发报错。

修改后的完整代码示例

# 先处理订单参考值的提取,避免filtered_df为空时item()报错
try:
    order_ref = filtered_df['ORDER_REF_STR'].item()
except ValueError:
    # filtered_df为空,直接生成空DataFrame
    CurrentBOM = merged_Plan_BOM_df.iloc[0:0]
else:
    # 执行原过滤逻辑
    CurrentBOM = merged_Plan_BOM_df.loc[merged_Plan_BOM_df['ORDER_REF_STR'] == order_ref]

# 可视化部分增加空值判断
with st.container():
    if not CurrentBOM.empty:
        col2.dataframe(CurrentBOM, width=100, height=1000)
    else:
        col2.markdown("**未找到匹配的BOM数据**")

关键细节说明

  • 用DataFrame.empty属性判断是否为空,这是Pandas官方推荐的空DataFrame检测方法。
  • 增加try-except块处理filtered_df['ORDER_REF_STR'].item()的潜在崩溃:如果filtered_df为空,item()会抛出ValueError,提前捕获并生成空DataFrame,阻断后续报错链。
  • 空DataFrame场景下用markdown输出提示,替代直接传入空DataFrame到st.dataframe,从根源解决报错问题。

内容的提问来源于stack exchange,提问作者Dawid Magdoń

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 17:55:18