I have the following use case for which I’d like to build a streamlit UI: I have two lists of inputs, and I’d like to represent the cartesian product of those inputs in a table. Ideally, I take accept inputs in those lists with the following UI: The top row and leftmost column of the table are inputs, and then each cell in the table is the combination of the corresponding row and column input. The user should be able to add rows or columns to add more inputs as well. Is this possible?
You can loop for each row and access the values of the the input boxes using their keys to get something like this:
And the number of inputs (rows or columns) can be controlled with an additional input field for those values.
Code:
import streamlit as st
with st.sidebar:
NX = st.number_input("Number columns", 1, 10, 4, 1)
NY = st.number_input("Number rows", 1, 10, 3, 1)
## Define list of parameters
x_list = [*"abcdefghij"][:NX]
y_list = [*"xyzmnpqrst"][:NY]
## Write the first row of number inputs
cols = st.columns(len(x_list) + 1)
for x, col in zip(x_list, cols[1:]):
with col:
st.number_input(f"${x}$", 0.0, 1.0, 0.5, 0.1, key=x)
"****"
## For each new row, start with a number input and
## write the the corresponding product
for y in y_list:
cols = st.columns(len(x_list) + 1)
with cols[0]: # The first column is an input field
st.number_input(f"${y}$", 0.0, 1.0, 0.5, 0.1, key=y)
for x, col in zip(x_list, cols[1:]): # The rest of the columns are for results
with col:
xval = st.session_state[x]
yval = st.session_state[y]
st.metric(f"$({x},{y})$", f"({xval:.1f},{yval:.1f})")
"****"
Although that example is a bit cursed. For simple inputs, you might want to use a st.data_editor. It will allow you to add or delete elements easier too.
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.