Updating starting dataframe in experimental_data_editor

When you use ‘Create New’ you are reliably getting an empty dataframe with just the column labels. Rerunning the page doesn’t change what that empty dataframe looks like. The problem with the randomly generated one is the actual “random” part; it would have different values/data with each page load and thus create a new data editor with each page load.

So long as you don’t change what you have passed to the data keyword parameter, the data editor will remain stateful and keep track of the edits. If you want to save those edits so you can navigate to another page, or retain the info while passing something different to data, then yes, you would need to push the edited dataframe to session state in some way.

Whenever you are changing some creation parameter of a widget (in this case the dataframe passed to data), you have to carefully work through the order of operations.

Consider:

import streamlit as st
import pandas as pd

if 'df' not in st.session_state:
    st.session_state.df = pd.DataFrame([0])

edited_df = st.experimental_data_editor(st.session_state.df)

st.session_state.df = edited_df
  1. The page initializes and we have a dataframe with a single cell having value 0.
  2. You change the value 1.
  3. The page reloads with the dataframe in session state still have value 0.
  4. When the script gets to the data editor, the data input still has 0, but the edited output now has 1.
  5. The script ends by overwriting the dataframe in session state, so it now has 1 as well.
  6. Now you change the value to 2.
  7. The page reloads with the dataframe in session state having value 1.
  8. When the script gets to the data editor, it sees that there is now a new value for data. Hence the state of the previous data editor is discarded (bye-bye 2), and you get a new data editor starting fresh with a value of 1.

Here is an example with an added step to get around this:

2 Likes