If syntax error while attempting to incorporate in a st.select_slider()

Hi,

I am trying to use an if function with a slider.
The aim of “if” is to adjust the slider range to change based on the region chosen.
The aim is to get the min and max value of common column shared by three databases based on the region chosen (chosen region is mapped under g)

For some reason I am getting a syntax error for if
indentations look to be ok
I use “==” instead of “=”
and I have elif and else mapped with a task in case

Code

minvalue1,maxvalue1=st.select_slider(
if g == ‘Americas’:
df(min(AmericasDatabase[parameter1]),max((AmericasDatabase[parameter1])))
elif g== ‘Europe’:
df(min(EuropeDatabase[parameter1]),max((EuropeDatabase[parameter1])))
else:
df(min(AsiaPacificDatabase[parameter1]),max((AsiaPacificDatabase[parameter1]))))

Screenshot 2022-12-04 at 6.12.46 PM

You won’t be able put the if function inside st.slider like that. A better approach is to do your computation first to get your min_value and max_value first, saving them in variables, then create the slider and pass them in. Also, don’t forget to give st.slider a label so something like:

st.slider('Choose one:', min_value, max_value)

I see an issue with your determination of min and max, too. For example, in the first Americas case, AmericasDatabase[parameter1] is a Series. I see you get the min and max of it, but then you do something with df that I’m not sure what your intention was. df(min_value, max_value) doesn’t make sense to me. If df is a DataFrame, you will get an object is not callable error with that.

PS. Make sure you use code formatting so we can see your indentations correctly. Use the tick mark on the ~ button to single quote inline or triple quote for a code block. Like this

and
like
this

image

thanks for the feedback @mathcatsand

St.select_slider is not compatible with “if” in general?
The reason I am trying to embed an “if” in the form is to adjust its “range” based on another forms result.
How can I use one “forms” result to influence the options given in another “form”?

Should I embed the form in the “if” then? i.e. if a>1 show form A else show form B?

It’s not about the slider, it’s just Python syntax in general. (Maybe you are a heavy SQL user?)

In Python, you can’t substitute in a raw if-else clause where you want some conditional value. You can however define a function that runs the if-else clause and returns the result, then use that function where you want the result. For example

condition = st.radio('Condition', [1,2,3])

def get_min_max(condition):
    if condition == 1:
        return (0,1)
    elif condition == 2:
        return (10,20)
    else:
        return (200,300)

# Option 1
# * is used to unpack the tuple into two separate objects
st.slider('Choose:',*get_min_max(condition), value = get_min_max(condition)[0], key='opt1')
# Option 2
# min and max are pulled out of the tuple by index
st.slider('Choose:',get_min_max(condition)[0],get_min_max(condition)[1], value = get_min_max(condition)[0], key='opt2')
# Option 3
# Get min, max saved to variables and use those variables
min_value, max_value = get_min_max(condition)
st.slider('Choose:',min_value, max_value, value=min_value, key='opt3')

There is also a fiddly detail with changing the boundaries of a widget. Either use a key with a time stamp so Streamlit disassociates itself from previous page loads, or manually deal with the value argument because otherwise it could stay on a number that is no longer valid for the current available range. (If you remove the value argument from the three examples, you’ll see what I mean since I set each range of numbers to be exclusive of each other.)

There are lots of ways to tie options together. You may need to look into session state and callback functions depending on how much interaction you are hoping to get.

If you want to take the user through some stages of selection (“Choose this first, then this, then that.”), I have a snippet here that will conditionally display the next bit of instructions or options for users.

And oops, I started off coding an example with select_slider and I guess my brain just reverted. So instead of passing a min and max value, you’d pass the list of values. I can adapt the example, but how were you wanting to use the min and max to extract the list of options? Were you wanting to apply a filter to a dataframe column to get the list of values within that range?

thank you @mathcatsand

The sequence I aim for is the following:
Step 1: Use “1st form” and “Chose a region”
Step 2: Use “2nd form” to receive filters per column and apply it to the relevant “region database” that was chosen from the “1st form”.
***The min/max range I would like to create is to ensure that the correct range will be used per column type. But at this end of the day this is not a very important feature.

Ideally I would have like to merge the two forms in one, but I am not sure how to application of the filters to the correct database form will work. So basically you are saying the only way to dynamically return the correct database is just to create a function which returns the correct database?

So maybe something like this:

import streamlit as st
import numpy as np
import pandas as pd

if 'df' not in st.session_state:

    region_list = []
    year_list = []
    value_list = []

    for i in range(5):
        beginning = np.random.randint(1990,2020)
        end = beginning + np.random.randint(5,20)
        for y in range(beginning, end+1):
            region_list.append(f'Region {i+1}')
            year_list.append(y)
            value_list.append(np.random.random()) 

    df = pd.DataFrame({'Region':region_list,'Year':year_list,'Value':value_list})
    st.session_state['df'] = df

df = st.session_state['df']

columns = st.columns(2)

with columns[0]:
    region = st.selectbox('Region',df.Region.unique())
    year = st.select_slider('Year',df[df['Region']==region].Year.unique())

    st.write(f'The selected region is {region}.')
    st.write(f'The selected year is {year}.')

    df[df['Region']==region][df['Year']==year]

with columns[1]:
    st.write('The full data frame is:')
    df

In this case, if you change a selection higher up, the ones following with be reset.

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