How to save the displayed dataframe after user select from the selectbox using st.session_state

how to save or create a persist dataframe that its not changed on each selection or click of a button Because on each click the code is rerun from the beginning from top to down.

what i want is to save the created dataframe using st.session_state but i don’t know how to use it yet.

what I want is to do something similar to the incremental number below But instead i want to make it to the df_result_search

code:

import pandas as pd
import streamlit as st

df_result_search = pd.DataFrame.from_records(rows, columns = [column[0] for column in cursor.description])

if 'count' not in st.session_state:

      st.session_state.count = 0
     st.write("you are out of  the session")
else:
      st.write("you are in the session")
st.dataframe(df_result_search)

df_len = range(len(df_result_search.index))
s = st.selectbox('Select index',options=df_len)
st.write(s)
expander_updates_fields = st.beta_expander('Update Records')
with expander_updates_fields:
          for i, col in enumerate(df.columns):
                    val_update = st_input_update('Update {} from {} to:'.format(col, df[col].values[s]))
                    expander_updates_fields.markdown(val_update, unsafe_allow_html=True)
if st.button("Increment"):    
          st.session_state.count += 1
st.write('Count = ', st.session_state.count)

so how this can be done ??

Hey @leb_dev ,
You can do the following to work with SessionState:

  1. Copy this SessionState code (SessionState.py) into a .py file and name it SessionState.py in your project folder
  2. import SessionState and initialiaze count in sessionstate like the following:
import SessionState
ss = SessionState.get(count=0)
  1. Afterwards, to keep the value of count make sure you increment it from sessionstate variable ss.

Let’s us know if this helped you out !

I tried your answer and this what i wrote:

ss = SessionState.get(count=0)
if st.button("Increment"):    
      ss += 1
st.write('Count = ', ss)

it display the below error:

TypeError: unsupported operand type(s) for +=: 'SessionState' and 'int'

Traceback:

File "F:\AIenv\lib\site-packages\streamlit\script_runner.py", line 349, in _run_script
    exec(code, module.__dict__)File "f:\AIenv\streamlit\app2.py", line 1097, in <module>
    main()File "f:\AIenv\streamlit\app2.py", line 522, in main
    ss += 1

Hey @leb_dev ,
In order for the incrementation to work you have to increment ss.count instead of ss, like the following:

import streamlit as st
import SessionState

ss = SessionState.get(count=0)
if st.button("Increment"):    
    ss.count += 1
st.write('Count = ', ss.count)

increment
By implementing the code above, it should be working.

Let us know if this helped you out !

so how about save or preserve the dataframe after the change in selectbox as i asked in my question

In order to keep your dataframe persistent, you can add a second variable inside sessionstate and give your dataframe as a value. Let’s add this to our previous program:

import streamlit as st
import numpy as np
import SessionState

dataframe = np.random.randn(10, 20)
ss = SessionState.get(count=0, df=dataframe)
st.dataframe(ss.df)


if st.button("Increment"):    
    ss.count += 1
st.write('Count = ', ss.count)

We have created a random dataframe and we persisted it in a way that it won’t change when our page refreshes.

Let us know if this helped

i tried your answer but it display the below error:

AttributeError: 'SessionState' object has no attribute 'df'

Traceback:

File "F:\AIenv\lib\site-packages\streamlit\script_runner.py", line 349, in _run_script
    exec(code, module.__dict__)File "f:\AIenv\streamlit\app2.py", line 1142, in <module>
    st.dataframe(ss.df)

I had the same error at first, but it was solved by reloading the page and/or changing the name of the dataframe inside sessionstate.

Keep us updated!

Hi @leb_dev,

Here’s an example I put together demonstrating how to delete columns from a dataframe based on user input, and store the resulting dataframe as Session State variable.

import pandas as pd
import streamlit as st

@st.cache
def load_data():
    df = pd.read_csv("https://github.com/selva86/datasets/raw/master/Auto.csv")
    return df

# callback to remove column from dataframe and store result in session state
def persist_dataframe():
    # drop column from dataframe
    delete_col = st.session_state["delete_col"]
    if delete_col in st.session_state["updated_df"]:
        st.session_state["updated_df"] = st.session_state["updated_df"].drop(
            columns=[delete_col]
        )
    else:
        st.sidebar.warning("Column previously deleted. Select another column.")
    with col2:
        st.write("Updated dataframe")
        st.dataframe(st.session_state["updated_df"])
        st.write(st.session_state["updated_df"].columns.tolist())

df = load_data()

# initialize session state variable
if "updated_df" not in st.session_state:
    st.session_state.updated_df = df

# display original df in col1 and updated df in col2
col1, col2 = st.beta_columns(2)

with col1:
    st.write("Original dataframe")
    st.dataframe(df)
    st.write(df.columns.tolist())

with st.sidebar.form("my_form"):
    index = df.columns.tolist().index(
        st.session_state["updated_df"].columns.tolist()[0]
    )
    st.selectbox(
        "Select column to delete", options=df.columns, index=index, key="delete_col"
    )
    delete = st.form_submit_button(label="Delete", on_click=persist_dataframe)

Output:
state-pandas-save

Best, :balloon:
Snehan

about the error above you were right i need to refresh the page.
But when i tried you answer into my code it still not working and the dataframe is not persist.

code:


import streamlit as st 
import pandas as pd

df = pd.read_sql_query('select * from testDB.dbo.t1',con)
with st.form(key='Search_form'):
       all_columns = df.columns.tolist()
       st_input_update = st.number_input if is_numeric_dtype(all_columns) else st.text_input
       search_term=st_input_update("Enter Search Term")
       if st.form_submit_button("search"):
              if len(search_term)>0:
                   sql='select * from testDB.dbo.t1 where  last LIKE  ? or first LIKE ?  '
                   param0=f'%{search_term}%'
                   param1=f'%{search_term}%'
                   rows = cursor.execute(sql, param0,param1).fetchall()
              df_result_search = pd.DataFrame.from_records(rows, columns = [column[0] for column in cursor.description])
 ss = SessionState.get(df=df_result_search)
 st.dataframe(ss.df)     
 df_len = range(len(df_result_search.index))
 s = st.selectbox('Select index',options=df_len)
st.write(s)
expander_updates_fields = st.beta_expander('Update Records')
with expander_updates_fields:
        for i, col in enumerate(df.columns):
               val_update = st_input_update('Update {} from {} to:'.format(col, df[col].values[s]))
               expander_updates_fields.markdown(val_update, unsafe_allow_html=True)
1 Like

So if i want to apply your code into mine is this how it can be wrote ?

code:

import streamlit as st 
import pandas as pd 

df = pd.read_sql_query('select * from testDB.dbo.t1',con)
with st.form(key='Search_form'):
       all_columns = df.columns.tolist()
       st_input_update = st.number_input if is_numeric_dtype(all_columns) else st.text_input
       search_term=st_input_update("Enter Search Term")
       if st.form_submit_button("search"):
              if len(search_term)>0:
                   sql='select * from testDB.dbo.t1 where  last LIKE  ? or first LIKE ?  '
                   param0=f'%{search_term}%'
                   param1=f'%{search_term}%'
                   rows = cursor.execute(sql, param0,param1).fetchall()
              df_result_search = pd.DataFrame.from_records(rows, columns = [column[0] for column in cursor.description])
              st.session_state["df_result_search"]
 
if 'df_result_search' not in st.session_state:
          st.session_state.df_result_search = df_result_search
          st.write("you are out of  the session")
else:
          st.write("you are in the session")
          st.session_state.df_result_search = df_result_search
                        
st.dataframe(st.session_state["df_result_search"])

df_len = range(len(df_result_search.index))
s = st.selectbox('Select index',options=df_len)
st.write(s)

expander_updates_fields = st.beta_expander('Update Records')
with expander_updates_fields:
          for i, col in enumerate(df.columns):
                   val_update = st_input_update('Update {} from {} to:'.format(col, df[col].values[s]))
                   expander_updates_fields.markdown(val_update, unsafe_allow_html=True)