pythonstreamlitcovariance-matrix

ValueError: The truth value of a Index is ambiguous. Use a.empty, a.bool(), a.item(), a.any()


I am writing this code for streamlit deployment:

if show_covariance_matrix:
    if not cov_matrix.columns.empty:
        fig = ff.create_annotated_heatmap(z=cov_matrix.values, x=cov_matrix.columns.tolist(), y=cov_matrix.index, colorscale='Viridis')
        st.plotly_chart(fig)

I want the covariance matrix to be interactive. But I get this error:

ValueError: The truth value of a Index is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

show_covariance_matrix is defined as

show_covariance_matrix = st.sidebar.checkbox("Show cov matrix")

This is the error traceback:

File "C:\Users\app.py",    line 556, in _run_script
    exec(code, module.__dict__)
File "C:\Users\app.py",    line 183, in <module>
    main()

File "C:\Users\app.py", line 50, in main
    fig = ff.create_annotated_heatmap(z=cov_matrix.values, x=cov_matrix.columns.tolist(), y=cov_matrix.index, colorscale='Viridis')

File "C:\Users\app.py", line 101, in create_annotated_heatmap
    validate_annotated_heatmap(z, x, y, annotation_text)

File "C:\Users\app.py",   line 41, in validate_annotated_heatmap
    if y:

File "C:\Users\app.py",   line 2809, in __nonzero__
    raise ValueError(

I have tried reworking with the code but it did not fix it.


Solution

  • create_annotated_heatmap tries to check whether a y value was provided to it, using if y:. This makes sense for most sorts of inputs, such as lists. However, it will not work for an Index (or Series, or DataFrame, or a Numpy array), because of special protections built in to those types.

    Convert the Index to a list first - just as with the x parameter.