How to use streamlit variable into other if-else condition statement

I’m working with streamlit for my web application.

import streamlit as st
import pandas as pd
l=[]
COLUMNS_SELECTED = None
Data = None
r = pd.DataFrame()
Data_df = pd.DataFrame()


def filter_df(columns_name,df):    
    df = df[columns_name]
    return df

uploaded_file = st.file_uploader("Choose a file")
if uploaded_file is not None:
    df = pd.read_excel(uploaded_file)
    COLUMNS_SELECTED = st.multiselect('Select options', df.columns.to_list())
      
if COLUMNS_SELECTED:
      Data = filter_df(COLUMNS_SELECTED, df)
      Data_df = Data_df.append(Data)
      
button_sent_1 = st.button("Button 1")

if button_sent_1:
    st.write("Data_df shape",Data_df.shape)
    r = r.append(Data_df)
    st.write("AP_data shape",r.shape)
    

button_sent_2 = st.button("Button 2")

if button_sent_2:
    st.write("Data_df shape",Data_df.shape)
    st.write("AP_Data shape",r.shape)]

I am returning the shape of data in with two buttons for varible “Data_df” and “AP_Data”.In “button A” I am appending Data_df into another dataframe “AP_Data” and want to use in “Button B” but its returning empty dataframe. I am able to use “Data_df” varible in same way as I am using “AP_Data”.

I am also attaching screenshots of my web application for the reference.

Hello,

This is the way Steamlit works - every time you press a button, whole script is rerun, so your r variable will be reset to empty DataFrame.

The only solution I am aware of is this:

  1. Put this file in the same directory as your main app link and name it SessionState.py

  2. Your code should have small changes:

import streamlit as st
import SessionState
import pandas as pd
ss = SessionState.get(r = pd.DataFrame())

l=[]
COLUMNS_SELECTED = None
Data = None
Data_df = pd.DataFrame()

def filter_df(columns_name,df):

 df = df[columns_name]

 return df

uploaded_file = st.file_uploader("Choose a file")

if uploaded_file is not None:

 df = pd.read_excel(uploaded_file)

 COLUMNS_SELECTED = st.multiselect('Select options', df.columns.to_list())
if COLUMNS_SELECTED:

   Data = filter_df(COLUMNS_SELECTED, df)

   Data_df = Data_df.append(Data)
button_sent_1 = st.button("Button 1")

if button_sent_1:

 st.write("Data_df shape",Data_df.shape)

 ss.r = ss.r.append(Data_df)

 st.write("AP_data shape",ss.r.shape)
button_sent_2 = st.button("Button 2")

if button_sent_2:

 st.write("Data_df shape",Data_df.shape)
 st.write("AP_Data shape",ss.r.shape)
 st.write(ss.r)

Or you can try using decorator @st.cache

Thanks @De_Stroy it works