1

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.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • Not enough details. How is `show_covariance_matrix` defined? What's the full trackback? etc. – tdy Feb 12 '23 at 05:58
  • Probably `show_covariance_matrix` is returning a pandas Series, so using it with `if` throws that error. Without details, we can only guess though. – tdy Feb 12 '23 at 06:00
  • I think you need `y=cov_matrix.index.tolist()` just like you did on the `x` parameter. The API is likely just interested in whether there is anything line the list, but indexes don't work that way on boolean tests. – tdelaney Feb 12 '23 at 19:20
  • Hint: where the code says `cov_matrix.columns.tolist()`, what was the purpose of the `.tolist()` part? Would it have worked without that? Why not? Do you see why similar logic might apply to the `y` value, as for the `x`? – Karl Knechtel Feb 13 '23 at 12:54

1 Answers1

0

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.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153