The problem happens when you try to assign the streamlit sidebar to a pandas' DataFrame column.
That's why, when you allow the execution to continue with the try/except block, the sidebar is set, but the exception is raised anyway.
Put in other words, if you separate the problematic line in two, you would have the following:
sidebar = st.sidebar.multiselect('Filter '+y, columns) # <-- This line is OK
data[y+"filter"] = sidebar # <-- This line fails
That line fails because data
is a pandas' DataFrame and therefore data[y+'filter'] is a column. And you cannot assign one element to a column, which is what's stated in the quite cryptic error message:
ValueError: Length of values (0) does not match length of index (97)
Which means that your dataframe has 97 rows and you are assigning a standalone element (with "length 0").
When you wrap the line in a try/except block, the part that works (AKA: st.sidebar.multiselect('Filter '+y, columns)
) is executed and that's why you do get the sidebar: because the error happens right after creating it.
You can solve the problem by gathering the references to the sidebars in a dictionary
sidebars = {}
for y in data.columns:
if (data[y].dtype == np.object):
ucolumns=list(data[y].unique())
sidebars[y+"filter"]=st.sidebar.multiselect('Filter '+y, ucolumns)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…