Skip to content
Topics
Streamlit
[Explained] Streamlit Selectbox: Usage, Parameters, and Examples

[Explained] Streamlit Selectbox: Usage, Parameters, and Examples

Streamlit has revolutionized the way Python developers create data applications. It's a powerful open-source library that allows developers to turn data scripts into shareable web apps in just a few lines of code. One of the key features of Streamlit is its interactive widgets, and among them, st.selectbox stands out due to its versatility and widespread use.

st.selectbox is a widget that displays a select box in your Streamlit app. It allows users to select an option from a dropdown menu, making it a great tool for enhancing the interactivity of your app. But how does it work, and how can you make the most out of it? Let's dive in and explore.

Have you heard of this awesome Data Analysis & Data Visualisation tool, that can easily turn your Streamlit App into Tableau?

PyGWalker (opens in a new tab) is a Python Library that helps you easily embed a Tableau-like UI into your own Streamlit app effortlessly. Check out this amazing video produced by Sven from Coding is Fun (opens in a new tab) demonstrating the detailed steps for empowering your Streamlit app with this powerful Data Visualization Python Library!


Special Thanks to Sven and his great contribution (opens in a new tab) to PyGWalker community!

Additionally, you can also check out PyGWalker GitHub Page (opens in a new tab) for more PyGWalker examples.

Understanding st.selectbox

What is st.selectbox?

st.selectbox is a function in Streamlit that creates a select box widget. It's a user interface element that displays a list of options to the user. The user can select one option from the list, which can then be used in the app for various purposes, such as filtering data, selecting models, or controlling visualizations.

import streamlit as st
 
option = st.selectbox(
    'How would you like to be contacted?',
    ('Email', 'Home phone', 'Mobile phone')
)
st.write('You selected:', option)

In this example, st.selectbox creates a select box with three options: 'Email', 'Home phone', and 'Mobile phone'. The selected option is stored in the variable option, which can then be used elsewhere in the code.

Parameters of st.selectbox

st.selectbox takes several parameters to control its behavior:

  • label: A string that will be used as the select box label.
  • options: A list of options to display in the select box. This can be any valid Python list or array-like object.
  • index: The index of the default selected option. If not provided, the first option will be selected by default.
  • format_func: A function that takes an option as an argument and returns a string representation of it. This is useful if you want to display options in a specific way.

What does st.selectbox return?

st.selectbox returns the currently selected option. This can be a string, a number, or any other type of object, depending on the options you provided. This returned value can then be used in your app, for example, to filter a DataFrame, control a visualization, or trigger a calculation.

Working with st.selectbox

How to use st.selectbox

Using st.selectbox is straightforward. First, you need to import the Streamlit library. Then, you can call st.selectbox with the label and options parameters. The selected option will be returned by the function.

import streamlit as st
 
## Define the options
options = ['Option 1', 'Option 2', 'Option 3']
 
## Create the select box
selected_option = st.selectbox('Choose an option:', options)
 
## Display the selected option
st.write('You selected:', selected_option)

In this example, the select box will display the options 'Option 1', 'Option 2', and 'Option 3'.

Examples of st.selectbox Usage

Streamlit's st.selectbox is a versatile widget that can be used in a variety of scenarios. Let's explore some examples to understand its usage better.

Example 1: Data Filtering

One common use of st.selectbox is to allow users to filter data. For instance, if you have a DataFrame containing information about different countries, you could use st.selectbox to let the user select a country and display only the data for that country.

import streamlit as st
import pandas as pd
 
## Load the data
data = pd.read_csv('data.csv')
 
## Get the list of countries
countries = data['Country'].unique()
 
## Create the select box
selected_country = st.selectbox('Choose a country:', countries)
 
## Filter the data
filtered_data = data[data['Country'] == selected_country]
 
## Display the filtered data
st.write(filtered_data)

In this example, st.selectbox is used to create a dropdown menu with the unique countries from the DataFrame. The user's selection is then used to filter the DataFrame and display only the data for the selected country.

Example 2: Model Selection

Another common use of st.selectbox is in machine learning applications, where it can be used to allow the user to select a model. For instance, if you're building a classification app, you could use st.selectbox to let the user choose between different classifiers.

import streamlit as st
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
 
## Define the models
models = {
    'Random Forest': RandomForestClassifier(),
    'SVM': SVC()
}
 
## Create the select box
selected_model = st.selectbox('Choose a model:', list(models.keys()))
 
## Get the selected model
model = models[selected_model]
 
## Use the model...

In this example, st.selectbox is used to create a dropdown menu with the available models. The user's selection is then used to retrieve the corresponding model from the dictionary.

Exploring Other Streamlit Widgets

While st.selectbox is a powerful widget, Streamlit offers many other widgets that can be used to create interactive applications. Let's explore a couple of them.

st.checkbox

st.checkbox is another useful Streamlit widget. It creates a checkbox that the user can check or uncheck. Like st.selectbox, st.checkbox returns the current state of the checkbox, which can be used in your app.

import streamlit as st
 
## Create the checkbox
is_checked = st.checkbox('Check me')
 
## Display the state of the checkbox
st.write('The checkbox is', 'checked' if is_checked else 'unchecked')

st.slider

st.slider is a widget that creates a slider. The user can move the slider to select a value within a specified range. st.slider returns the current value of the slider.

import streamlit as st
 
## Create the slider
value = st.slider('Select a value', 0, 100, 50)
 
## Display the selected value
st.write('You selected:', value)

These are just a few examples of the many widgets available in Streamlit. By combining these widgets, you can create highly interactive and user-friendly applications.

Advanced Usage and Considerations

Streamlit's st.selectbox is a powerful widget, but there are some advanced usage and considerations that you should be aware of to make the most out of it.

Enabling/Disabling Text Search in st.selectbox

One of the features of st.selectbox is that it allows users to search for options by typing text. This can be very useful when the select box has a large number of options. However, in some cases, you might want to disable this feature. As of now, Streamlit does not provide a built-in way to disable text search in st.selectbox, but this might change in future versions of the library.

Default Value and Index

By default, st.selectbox selects the first option in the list. However, you can change the default selected option by using the index parameter. The index parameter takes an integer that represents the index of the option to be selected by default.

import streamlit as st
 
# Create the select box with 'Option 2' selected by default
selected_option = st.selectbox('Choose an option:', ['Option 1', 'Option 2', 'Option 3'], index=1)
 
# Display the selected option
st.write('You selected:', selected_option)

In this example, 'Option 2' is selected by default because its index (1) is passed to the index parameter.

Custom Formatting with format_func

st.selectbox allows you to customize how the options are displayed using the format_func parameter. format_func is a function that takes an option as input and returns a string representation of it.

import streamlit as st
 
# Define a format function
def format_func(option):
    return option.upper()
 
# Create the select box with custom formatting
selected_option = st.selectbox('Choose an option:', ['Option 1', 'Option 2', 'Option 3'], format_func=format_func)
 
# Display the selected option
st.write('You selected:', selected_option)

In this example, the options are displayed in uppercase thanks to the format_func parameter.

Conclusion

Streamlit's st.selectbox is a versatile and powerful widget that can greatly enhance the interactivity of your Python apps. Whether you're building a data visualization tool, a machine learning application, or any other type of interactive app, st.selectbox can make your app more user-friendly and intuitive. So go ahead, experiment with st.selectbox, and see how it can improve your Streamlit apps!

Have you heard of this awesome Data Analysis & Data Visualisation tool, that turns your Streamlit App into Tableau?

PyGWalker (opens in a new tab) is a Python Library that helps you easily embed a Tableau-like UI into your own Streamlit app effortlessly.

PyGWalker for Data visualization in Streamlit (opens in a new tab)

Frequently Asked Questions

  1. What is the default value of st.selectbox in Streamlit? By default, st.selectbox selects the first option in the list. However, you can specify a different default option using the index parameter.

  2. How can I customize the display of options in st.selectbox? You can customize how the options are displayed in st.selectbox using the format_func parameter. format_func is a function that takes an option as input and returns a string representation of it.

  3. Can I disable the text search feature in st.selectbox? As of now, Streamlit does not provide a built-in way to disable the text search feature in st.selectbox. However, this might change in future versions of the library.