Hi, thanks to you, I manage to create a app with a weights input but I would like that the weights sum to One in the num ber_input ie that automatically the last weight is equaled to 1-sum(previous weights) each time I change a weight
This is what I did:
weights = {}
for col in selected_indices:
weights[col] = st.sidebar.number_input(label=f"{col} weight",
min_value=0,
max_value=100,
step=5,
value=int(100/len(selected_indices))
)
To ensure that the sum of weights is always 1, you can update the last weight value each time a weight is changed using the on_change event of the number_input widget.
Here is an updated version of your code that implements this:
weights = {}
for col in selected_indices:
weights[col] = st.sidebar.number_input(label=f"{col} weight",
min_value=0,
max_value=100,
step=5,
value=int(100/len(selected_indices))
)
# Update the last weight value whenever a weight is changed
if col == selected_indices[-1]:
for key in weights:
if key != col:
weights[col] = 100 - sum([weights[k] for k in weights if k != col])
And last question concerning your solution : does it change the weights that are displayed ? Because it seems that is not the case…and how to change the weights that are displayed in number_input ?
I don’t think the on_change kwarg is necessary in that case because you are assigning the value to the last number_input based on the previous ones.
Here is a smaller example.
import streamlit as st
## Initialize the first four weights
weights = [ st.number_input(f"Weight {i}", 0.0, 1.0, value=0.0) for i in range(1, 4) ]
## Autocomplete the last one. (Disabling it is not required)
last_weight = st.number_input(f"Last weight", 0.0, 1.0, value=(1.0 - sum(weights)), disabled=True)
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.