Pandas Dataframe update cell value in SessionState

Hey guys,

quick question. Is there a way preserve a pandas dataframe while using SessionState?
I copyed the file (“sessionState.py”) into my project and load it.

However, if I do an update for one row of the dataframe, the previous values get lost.

state = SessionState.get(df=pd.DataFrame(), index =0)

if st.button("Next"):
state.df.at[state.index, 'Added Values'] = 1
state.index += 1

st.dataframe(state.df)

Any ideas why this is and how to solve it?

Thanks in advance.
Chris

Its because your state’s df and index variables are getting reset everytime your script executes,

you could do something like this,
( Assuming you are using Session State class from this gist https://gist.github.com/Ghasel/0aba4869ba6fdc8d49132e6974e2e662 )

state = SessionState()

if state.df is None:
    state.df = pd.DataFrame()

if state.index is None:
    state.index = 0
1 Like

Sounds pritty easy. The wired thing is, the state.index is not reseted. Only the df.
I took the file from here: https://gist.github.com/tvst/036da038ab3e999a64497f42de966a92 .
If i try to do

pages[page](state)

than it says that 0 parameters were required but one given.
Also state.snyc() does not work. Something is odd here.

Further, when I copy your code from the gist and do
state = _SessionState() I get:
TypeError: init() missing 2 required positional arguments: ‘session’ and ‘hash_funcs’

Any ideas how to solve that?

Hey @chris_klose

Please use the get_state function to get the state.
I like to use a small decorator that I wrote that takes care of get_state and sync state.
Check this out,

Also I like to put the “default configs” in the utils file like this, but it depends how you want to do it, https://github.com/ash2shukla/streamlit-heroku/blob/be0fd199cd772c7241f0aac1f59c626923c0df11/src/utils.py#L93

Hope it helps ! :slight_smile:

2 Likes