Filter without rerun the entire script

I have the following code:

import streamlit as st
import pandas as pd

#define data
d = {'id': ['a', 'b', 'c'], 'data': [3, 4,6]}
df = pd.DataFrame(data=d)

#create sidebar input
with st.sidebar.form("my_form"):
    a = st.slider('sidebar for testing', 5, 10, 9)
    calculate = st.form_submit_button('Calculate') 
 

if calculate:
    df['result'] = df['data'] + a 
    st.write(df)
    #no issues up to this point. When I move the slider in 10 the output in 16 stays on the web page

    ########debug############
    # I am trying to select an 'id' from the dropdown and use that to filter df, but when I select a value from the dropdown, 
    # the script runs again and the output disappears
    filter = st.selectbox('filter data', df['id'].unique())
    st.write(df[df['id'] == filter])

I would like to filter the Pandas dataframe using a drop down menu to select the id I am interested in, but when I use the drop down the code reruns.

Any idea how I can solve this?

PS I also tried enclosing the entire computation in a function and adding the @st.cache decorator, but without success. I would appreciate it if anyone could show me how it’s done.

Hi @luigi_cogliani ,

If I understood you correctly , probably putting, the filter outside the if loop will work,

if calculate:
    df['result'] = df['data'] + a 
    st.write(df)
filter = st.selectbox('filter data', df['id'].unique())
st.write(df[df['id'] == filter])

cheers
Avra

Wouldn’t this rerun the entire script when I use the select box, hence filtering the data frame before the computation took place?

Hi @luigi_cogliani ,
Ah, my previous answer was based on the dissapereance of the output. Apologies,

Let’s try this snippet below,

import streamlit as st
import pandas as pd

@st.cache(allow_output_mutation=True)
def create():
    d = {'id': ['a', 'b', 'c'], 'data': [3, 4,6]}
    df = pd.DataFrame(data=d)
    return df
df = create()
#create sidebar input
with st.sidebar.form("my_form"):
    a = st.slider('sidebar for testing', 5, 10, 9)
    calculate = st.form_submit_button('Calculate') 
 
if calculate:
    df['result'] = df['data'] + a 
    st.write(df)

filter = st.selectbox('filter data', df['id'].unique())
st.write(df[df['id'] == filter])
# Displaying the result consistently to be sure
st.table(df)

I hope this works out !

cheers,
Avra

thanks, worked like a charm!

1 Like