Last active
July 18, 2023 20:38
-
-
Save sdhutchins/fda9d1c0730839811abf618a190cf871 to your computer and use it in GitHub Desktop.
Create All option for multiselect
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import streamlit as st | |
import pandas as pd | |
def select_options(): | |
"""Select options based on the user's selection and update the session state. | |
This function is triggered when the selection of options changes. It checks if "All" is selected and updates | |
the session state accordingly. If "All" is selected, it sets the selected options to all options except "All", | |
and updates the maximum number of selections. If "All" is not selected, it updates the maximum number of selections | |
based on the available options. | |
Args: | |
None | |
Returns: | |
None | |
""" | |
if "selected_options" in st.session_state: | |
if "All" in st.session_state["selected_options"]: | |
st.session_state["selected_options"] = available_options[1:] | |
st.session_state["max_selections"] = len(available_options) - 1 | |
else: | |
st.session_state["selected_options"] = [] | |
st.session_state["max_selections"] = len(available_options) - 1 | |
existing_genes = ["Gene1", "Gene2", "Gene3", "Gene4", "Gene5"] | |
clinvar_accession_ids = ["CLINVAR1", "CLINVAR2", "CLINVAR3", "CLINVAR4", "CLINVAR5"] | |
df = pd.DataFrame({"Gene": existing_genes, "Clinvar Accession ID": clinvar_accession_ids}) | |
available_options = ["All"] + existing_genes | |
st.multiselect( | |
label="Select a Gene", | |
options=available_options, | |
key="selected_options", | |
max_selections=st.session_state["max_selections"], | |
on_change=select_options, | |
format_func=lambda x: "All" if x == "All" else x | |
) | |
if st.button("Clear Selection"): | |
st.session_state["selected_options"] = [] | |
selected_genes = available_options[1:] if st.session_state["max_selections"] == 1 else st.session_state["selected_options"] | |
filtered_df = df[df["Gene"].isin(selected_genes)] | |
st.dataframe(filtered_df) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
My gist is a modification of the example from Carlos D. Serrano at https://medium.com/streamlit/multi-select-all-option-in-streamlit-3c92a0f20526.