Create columns to a data_editor with data


Hello guys, i want to be able to type in a column name using text_input and then press a button for adding that column name as a column to a data_editor without the current data in the data_editor are disappearing.

Steps to reproduce

Code snippet:

def test_columns(col_name):
    first_key = next(iter(st.session_state["cso_df"]))  # Get the first key
    value_count = len(st.session_state["cso_df"][first_key])
    st.session_state["cso_df"][col_name] = [""] * value_count
    st.session_state.add_column = ""

def change_state2(edited_df):
    st.session_state["cso_df"] = edited_df

if create_scratch_options == 'create data without using a template':

   create_col = st.sidebar.text_input('add a column', placeholder="type a column name", 

   create_col_btn = st.sidebar.button('add the column', on_click=test_columns, args=(create_col,))

   if 'cso_df' not in st.session_state:
      st.session_state["cso_df"] = st.data_editor({'column1': [None],'column2': [None],'column3': [None]}, 
      num_rows='dynamic', use_container_width=True)

      st.session_state["cso_df"] = st.data_editor(st.session_state["cso_df"], num_rows='dynamic', 
      use_container_width=True, on_change=change_state2, args=(st.session_state["cso_df"],)) 

Expected behavior:

when i type in a column name and click the add button, i should see a new column being added to the data_editor with empty values, and the existing data i have already typed in to the data_editor should not disappear.

Actual behavior:

whenever i have data in the data_editor and create a new column, the column shows successfully, but all the existing data are being removed. So it just end up being an empty dataframe also containing the new column.

Debug info

  • Streamlit version: Streamlit, version 1.23.1
  • Python version: Python 3.9.5

Additional information

This issue definitely occur because of the architecture of how the data_editor is designed. Since it seems like the data_editor is not updated each time i add some data to it. I have also noted that if i add a column name then remove it again, press the background of my app(so the page loads) then type the column name again, and press the add button, then it works.

finally got it working.

The solution was to add the below line before adding columns to the st.data_editor:

st.session_state.some_key = edited_df 

where st.session_state.some_key is the input df to st.data_editor and edited_df is the value of the st.data_editor.

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