How to create a st.number_input that sums to 1

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))
                                           )

Thx

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])

Thx
I will try it…but you don’t use the « on_change » option of number_input ?

Cordialement

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 ?

Thx

Cordialement

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.

autochange_numberInput

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)

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