Deleted column in streamlit dropdown menu not updated immediately

I am trying to implement a “delete column” button for a csv file by means of a dropdownmenu form in streamlit. It works fine and removes the column, only the dropdownmenu list will not get updated until I refresh the page. I would like it to be done automatically.

File input.csv:



import streamlit as st
import pandas as pd

with st.form('Form1', clear_on_submit = True):
     st.session_state.df = pd.read_csv(r'./input.csv')
     column_name = st.selectbox('Delete column:', st.session_state.df.columns.tolist())         
     delete_column = st.form_submit_button('Delete this column') 
     if delete_column:                                        
          st.session_state.df.drop(str(column_name), axis=1, inplace=True)   
          st.session_state.df.to_csv(r'./input.csv', index = False)

Example: after deleting “col3”, it will still be visible in the dropdownmenu list until I refresh the page.


That is expected. Each time the script is rerun the data is read again from the csv file and any changes you made to it are lost. I guess you should not read from the file if "df" is already in session_state.

if "df" not in st.session_state:
    st.session_state.df = pd.read_csv(r'./input.csv')

Also having all that code inside the with block is probably harmless but I find it confusing. I think only the selectbox and the form_submit_button need to be there.

hi, sorry not working

Yeah, there is another issue. By the time you delete the column, the selectbox has already been instantiated and it won’t be aware of the change until the script is rerun. You can make the script rerun inmediately by calling st.experimental_rerun() right after deleting the column.

Also my initial advice was wrong, I didn’t notice that you are saving the data after deleting the column so you get the changes when you read it again.

Hi Goyo,

yes it works. To be honest I had already tried this solution and discarded it because I was not convinced by the fact that it is an experimental feature. Experimental features may change or be removed at any time. Do you not think this might be a drawback on the long term?