Using streamlit to accept row and column text inputs


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?

This is what I have so far, but I don’t know how to get the outputs to show up at the right cell in the table

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.

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.

import streamlit as st
import pandas as pd

## Initialize parameter inputs
x_list = {"Parameter": [*"abcd"]}
x_list["Values"] = [0.5] * len(x_list["Parameter"])

y_list = {"Parameter": [*"xyz"]}
y_list["Values"] = [0.5] * len(y_list["Parameter"])

## Display input space
cols = st.columns(2)
with cols[0]:
    "## Rows"
    x_data = st.data_editor(x_list, use_container_width=True, num_rows='dynamic')

with cols[1]:
    "## Columns"
    y_data = st.data_editor(y_list, use_container_width=True, num_rows='dynamic')

## Combine
x_times_y = [ [f"({x}, {y})" for x in x_data["Values"]] for y in y_data["Values"] ]

## Display result
df = pd.DataFrame(x_times_y, columns=x_data["Parameter"])
df.index = y_data["Parameter"]

"## Product"
st.dataframe(df, use_container_width=True)

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