Modifications to dataframe in session_state don't persist outside of function?

I have a DF in session state, and I run a function which does some maths and adds the results to new columns to the existing DF.

If I st.write the session state before the function, everything looks right.

If I st.write the state inside the function, after the maths, everything looks right - the DF has the additional columns.

But if I look at the session state after the function has run, the DF is back as it was originally, and nothing can address the new column. This is all in tabs and columns, so I have tried moving the function all over the place, but the same thing happens everywhere: the DF is only modified in the function, and not outside.

Which I am finding very confusing. Any ideas? Let me know if more detail would help! Thanks!

Would you be able to share a code snippet which demonstrates the issue?

I will try to make a runnable code demo later - given the complexity of the code, it will take a while to distill it down!

But, very pseudo-codey, it goes

def add_column():
    results = st.session_state.dataframe["column1"] * maths
    st.session_state.dataframe["result"] = results
    # debug, look at dataframe
    st.session_state.dataframe
    # the above line results in the df seen at the top of the screen in the shot below (which is correct)

#main stuff
#draw page
#bring data into session state
#run add_column
add_column()

#debug, look at dataframe
st.session_state.dateframe 
# above line displays df at bottom of screenshot below: incorrect, missing columns.

Here is what this is rendering: correct df at top of screen, when asked what it looks like inside the function. Incorrect dataframe at bottom of screen, after function has run.

Hey @altanner , thanks for the code snippet. Sorry for being slow to reply, but here is a simple example based on your pseudocode, and it seems to be working fine: https://playground.streamlitapp.com/?q=6f1123

I suspect there’s a different interaction going on, but am not sure what it might be.

One quick sanity you can do is to do st.write(st.session_state) at strategic points, to make sure you’re not accidentally saving your changes to an object with a different key than the original dataframe.

Not slow at all - all help is very useful.

Yeah, I think you are right, something strange is going on somewhere, but currently I cannot find it.

My workaround (I don’t really understand why it works!) is, at the end of the function which does some maths and puts it into a new column on the DF, is to then duplicate the DF entirely (luckily these things are not huge)… and the virgin DF is seen properly by the rest of the code :person_shrugging:

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