How to save new dataframe values version after session state update?

Hi there,

I’m working on a music recommendation app and I’d like to save in my dataframe the tracks that users listen to as they use the app, but somehow my dataframe keeps refreshing when the search bar gets updated.

Here is my original dataframe with the empty column ‘recos’ where I want to save the information when a track has been played:

dfm2 = pd.read_csv("df_matrix.csv")
dfm2['recos'] = pd.Series("")

Here’s what the column look like:

Here’s how my search bar is set up:

#Original track to start with:
OG = "Nirvana - Smells like teen spirit"
OG_index = int(dfm2[dfm2['artist_track'] == OG].index.values)
options = dfm2['artist_track']
search_bar = st.selectbox("", options, index = OG_index, label_visibility = "collapsed", key = "search")
player(search_bar)

Here’s what it looks like:

And here’s how my recommendations get updated:

#Callback functions to update the track displayed in the search bar
    def callback1():
        dfm2.loc[index_reco1, 'recos'] = reco1
        st.session_state.search = options[index_reco1]
        
    def callback2():
        st.session_state.search = options[index_reco2]

#Display of recommended tracks
    if search_bar != OG:
        st.write(f"You picked the track **{search_bar}**, here are our recommendations for you:")
        track = str(search_bar) 
        reco1 = reco(track)[0]
        reco2 = recom(track)[0]
        index_reco1 = int(dfm2[dfm2['artist_track'] == reco1].index.values)
        index_reco2 = int(dfm2[dfm2['artist_track'] == reco2].index.values)
        col1, col2 = st.columns([1,1])
        with col1:
            st.write(f"**{reco1}**")
            player(reco1)
            bouton1 = st.button('Next recommendation', on_click = callback1, key = 1)
        with col2:
            st.write(f"**{reco2}**")
            player(reco2)
            bouton2 = st.button('Next recommendation', on_click = callback2, key = 2)  
            
    st.dataframe(dfm2)

I’m only trying the save the “reco1” tracks for now, but the values in the column ‘recos’ get refreshed every time I select a new track.
I tried to reproduce what was suggested in this topic but it’s a tad too complex for me :grimacing:.

Any ideas on how I could save the info properly?

Many thanks!

1 Like

Would it be possible if you stored the dataframe as a csv or in a DB and recall it when you select new tracks?

I think that’s what I’ve been trying to do but I don’t know how :thinking:
Right now when I select a new track, the dataframe is being reset but that’s not what I want.

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