Retaining changes for Streamlit data editor when hiding or switching between widgets/pages – Streamlit

by
Ali Hasan
dataframe llama-cpp-python streamlit

Quick Fix: Initialize session state with original and edited dataframes. While on a page, have a data editor based on the original and save the edited result directly into session state with each edit. When the page is changed, copy the edited version in session state to overwrite the original one. Upon returning to the page, the data editor will start where the last edit ended.

The Problem:

In a Streamlit application with editable dataframes displayed in widgets or different pages, the edited changes are lost when switching between widgets or pages due to the rerunning of data generation functions. How can the edited dataframe information be retained so that it persists across these transitions and the user can continue editing the dataframe seamlessly?

The Solutions:

Solution 1: Save Edits on Page Change

Concept:
The data editor widget does not allow direct storage of its state, but its edited result can be saved. Update the edited result dataframe continuously while on a page, and overwrite the original dataframe when switching pages.

# Initialize session state with original dataframes and edited versions
st.session_state.df1 = pd.DataFrame(...)
st.session_state.edited_df1 = st.session_state.df1.copy()

# Save edits by copying edited dataframes to original slots
def save_edits():
    st.session_state.df1 = st.session_state.edited_df1.copy()

# Page selection with on_change=save_edits to commit changes
page = st.sidebar.selectbox("Select", ("A", "B"), on_change=save_edits)

if page == "A":
    st.session_state.edited_df1 = st.experimental_data_editor(...)
elif page == "B":
    st.experimental_data_editor(...)

Note: The .copy() method can be removed if the data editor is not performing modifications in place.

Q&A

How can I keep the changes made in the Streamlit data editor when switching between pages or hiding widgets?

Declare two dataframes in session state: an original and an edited version. Copy the edited version to the original version when the user leaves the page.

Why is it not possible to use @st.cache_data to store the edited data?

The data editor is a different type of widget and cannot be stored directly. Instead, save the result of edits and initialize a new editor with the previous state.

Video Explanation:

The following video, titled "Streamlit Multi-Pages - How to work with multiple pages(2022 ...", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

In this tutorial we will explore how to create multi-pages app with streamlit using the inbuilt streamlit-multi-pages feature. This is from ...