[SOLVED] How to pass data from one button to another?

I am uploading my datasets and with the click of a button it changes the data and then the next button click again changes the data.
The problem is it doesn’t take the updated data from the previous button click.
How do I achieve this ?
I tried to make the variable global also but it doesn’t work the way I want
The missing data and encoding function returns the dataframe after doing the operation

Here is the code:

def missing_data(training_data):
     
    training_data = training_data.fillna(training_data.mean())
    return training_data 
    

file2 = st.file_uploader('Upload Dataset')
if file2 is not None:
    data = load_data(file2)
    st.write('Training Data')
    training_data = train_data(data)
    st.write(training_data)
    st.write('Output Column')
    y = output_col(data)
    st.write(y)


if st.button('Mean'):
    training_data = missing_data(training_data)
            
    st.write(training_data)
         

if st.button('Encode'):
    training_data = encoding(training_data)
    st.write(training_data)

Hi @aniketwattamwar

The reason this happens is that clicking a button will only set its value to true for that one rerun of the script. For this reason, st.button is probably not the best widget for achieving the functionality you want.

The simplest way of achieving what you are after is probably replacing the button with a checkbox, like

def missing_data(training_data):
     
    training_data = training_data.fillna(training_data.mean())
    return training_data 
    

file2 = st.file_uploader('Upload Dataset')
if file2 is not None:
    data = load_data(file2)
    st.write('Training Data')
    training_data = train_data(data)
    st.write(training_data)
    st.write('Output Column')
    y = output_col(data)
    st.write(y)


if st.checkbox('Mean'):
    training_data = missing_data(training_data)
            
    st.write(training_data)
         

if st.checkbox('Encode'):
    training_data = encoding(training_data)
    st.write(training_data)

Hope that works for your needs :slight_smile:

2 Likes

Hi @PeterT

Thank you for this.
The checkbox workaround worked for me

Regards,
Aniket

This is amazing!