Persistence of Selected Column in Streamlit App

I’m developing a Streamlit app where users can select a column from a DataFrame, and I want to ensure that the selected column persists across interactions without resetting when selecting a different option

def display_unique_values(selected_column):
    st.write(f"Unique values in '{selected_column}':")
    st.write(df[selected_column].unique())      
        

if st.button('Generate Report'):
    try:
        excel_path = script.get_data(month, year)
        df = pd.read_excel(excel_path)
    
        selected_column = st.selectbox("Select a column", df.columns, key='selected_column')
        display_unique_values(selected_column)
        
    except Exception as e:
        error_message = f"Error retrieving data: {str(e)}"
        print(error_message)

I did try the session_state, but it also did not work

I’d appreciate any insights or suggestions on how to achieve this functionality effectively within a Streamlit app.

Thank you!

Why there is infinite loop?

1 Like

I was just trying thing so I added the loop but it didn’t do anything, and I learned afterwards that the whole page refreshes after selecting a different item in the selectbox,

I have edited it and removed the loop as it was not doing anything

1 Like

I was just trying thing so I added the loop but it didn’t do anything, and I learned afterwards that the whole page refreshes after selecting a different item in the selectbox,

I have edited it and removed the loop as it was not doing anything

Is your app uses the multi-page feature?

What is this different option?

Here is a sample that shows how to handle a button along with code reruns, etc.

import streamlit as st
from streamlit import session_state as ss
import pandas as pd


data = {
    'username': ['aaa', 'bbb', 'ccc'],
    'age': [25, 34, 42]
}


# A session variable to allow us to pass thru the button
# because a button state can become true once only after clicking it.
# Then button state goes back to false automatically.
# The selectbox behind the button can trigger code rerun and
# since there is a button above the selectbox and this button is
# now false we cannot reenter again on the selectbox and after it.
if 'button_ok' not in ss:
    ss.button_ok = False


def display_unique_values(df):
    st.write(f"Unique values in '{ss.selected_column}':")
    st.write(df[ss.selected_column].unique())
        

df = pd.DataFrame(data)

cols = st.columns([1, 1])
with cols[0]:
    # reruns the code from top to bottom after the button click
    if st.button('Generate Report'):
        ss.button_ok = True  # to see the select box
with cols[1]:
    if st.button('Clear'):
        ss.button_ok = False

if ss.button_ok:
    try:
        # reruns the code from top to bottom after selection
        st.selectbox(
            "Select a column",
            df.columns,
            key='selected_column'
        )
        display_unique_values(df)
        
    except Exception as e:
        error_message = f"Error retrieving data: {str(e)}"
        st.error(error_message)

No, it does not.

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