St.selectbox default suggestion with custom logic

Here is my dataframe:
df = pd.DataFrame({'Big Cat':[1,2,3], 'Big Dog':[2,3,4], 'Turtle':[1,2,3]})

I would like to create the following dropdown:
st.selectbox('Choose Dog', options=df.columns)

However, is there any chance to build the logic that my selectbox suggests a default value Big Dog instead of Big Cat as it is the first column in df, without explicitly indicating as follows:

st.selectbox('Choose Dog', options=df.columns, index = df.columns.tolist().index('Big Dog'))

Instead of Big Dog it can be Large Dog or Small Dog, therefore, I would like to have a custom suggestion in st.selectbox for any df.column that contains a word Dog in it.

Hey @serdar_bay,

Thanks for providing a code example so we can better help you!

I think a solution here is to find indices of df.columns for which the associated value contains β€œdog”. Then you can use one of these to pass to the index= parameter. See the embedded app below - make sure to expand the β€œSee code”:

Hope that helps!

Hi @arnaud - thanks for the reply.

Just one further point to optimize the code, what if dog is not contained in the name of columns, in that case, I would expect it to return the default dropdown as normal. However, it will cause an error - IndexError: list index out of range.

Perhaps, the dog example was not very good. In my real case, the column name can be Hookload, Weight on hook or even WOH depending on the client dataset, so if I indicate hookload as a default dropdown value and if the dataset came in with Weight on hook or WOH column, then it will cause an error.
As a solution, if I write a function with try-except clauses, can I pass a function to the index attribute in st.selectbox?

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.