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.
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”:
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?
Thanks for stopping by! We use cookies to help us understand how you interact with our website.
By clicking “Accept all”, you consent to our use of cookies. For more information, please see our privacy policy.
Cookie settings
Strictly necessary cookies
These cookies are necessary for the website to function and cannot be switched off. They are usually only set in response to actions made by you which amount to a request for services, such as setting your privacy preferences, logging in or filling in forms.
Performance cookies
These cookies allow us to count visits and traffic sources so we can measure and improve the performance of our site. They help us understand how visitors move around the site and which pages are most frequently visited.
Functional cookies
These cookies are used to record your choices and settings, maintain your preferences over time and recognize you when you return to our website. These cookies help us to personalize our content for you and remember your preferences.
Targeting cookies
These cookies may be deployed to our site by our advertising partners to build a profile of your interest and provide you with content that is relevant to you, including showing you relevant ads on other websites.