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

Streamlit部署交互式协方差矩阵时遇Index真值模糊ValueError

解决Streamlit中Plotly交互式协方差矩阵的ValueError问题

错误原因分析

报错信息ValueError: The truth value of a Index is ambiguous,回溯指向Plotly的validate_annotated_heatmap函数中对y参数的判断if y:。问题出在你传入的y=cov_matrix.index是pandas Index对象,而Plotly的create_annotated_heatmap函数在验证参数时,直接对Index对象做布尔判断会触发歧义(pandas不允许直接判断Index的真假,必须用.empty等方法)。

修复代码

只需将y参数从cov_matrix.index转换为列表即可,和你处理x参数的方式一致:

if show_covariance_matrix:
    # 同时检查列和索引是否非空,避免空矩阵报错
    if not cov_matrix.columns.empty and not cov_matrix.index.empty:
        fig = ff.create_annotated_heatmap(
            z=cov_matrix.values,
            x=cov_matrix.columns.tolist(),
            y=cov_matrix.index.tolist(),  # 转换为列表
            colorscale='Viridis'
        )
        st.plotly_chart(fig)

额外说明

  • Plotly的create_annotated_heatmap要求x和y参数为普通列表(或数组),而非pandas的Index/Columns对象,否则内部验证逻辑会触发pandas的布尔判断歧义错误。
  • 建议同时检查cov_matrix.index.empty,避免当矩阵只有列没有行时仍执行绘图逻辑导致其他潜在错误。

内容的提问来源于stack exchange,提问作者automorp15m

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 13:25:31