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]))))
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
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?
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?
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.
Thanks for stopping by! We use cookies to help us understand how you interact with our website.
By clicking “Accept all”, you consent to our use of cookies. For more information, please see our privacy policy.
Cookie settings
Strictly necessary cookies
These cookies are necessary for the website to function and cannot be switched off. They are usually only set in response to actions made by you which amount to a request for services, such as setting your privacy preferences, logging in or filling in forms.
Performance cookies
These cookies allow us to count visits and traffic sources so we can measure and improve the performance of our site. They help us understand how visitors move around the site and which pages are most frequently visited.
Functional cookies
These cookies are used to record your choices and settings, maintain your preferences over time and recognize you when you return to our website. These cookies help us to personalize our content for you and remember your preferences.
Targeting cookies
These cookies may be deployed to our site by our advertising partners to build a profile of your interest and provide you with content that is relevant to you, including showing you relevant ads on other websites.