Create data frame, add drop down option for each row and then allow user to add new rows

Hello @Ri_yaz, welcome to the forum!

When you post a code snippet, please post it as a code block, not as plain text – otherwise it’s very difficult to actually use the code and try to debug it. See this post for more: Using Streamlit: how to post a question in the Streamlit forum

If I correctly interpreted your code, the only issue was that setting the index of the selectbox was failing because the row wasn’t populated yet. I made a small tweak to default to 0 for the index, and it seems to work.

import pandas as pd
import streamlit as st

# Define column names for the empty dataframe
columns = ["Person_name", "Location", "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF"]
# Create an empty dataframe with the defined columns
empty_df = pd.DataFrame(columns=columns)
# Define a list of people to choose from
people = ["John", "Mary", "Jane", "Mark", "Lucy"]
# Create an empty session state variable
session_state = st.session_state
# Check if the session state variable is already defined
if "df" not in session_state:
    # Assign the initial data to the session state variable
    session_state.df = empty_df
    session_state.row = pd.Series(index=columns)

# Create a selectbox for each column in the current row
for col in columns:
    # Get unique values from the corresponding column in the resource_data dataframe
    if col == "Person_name":
        values = people
        values = ["Y", "N"]
    # Create a selectbox for the current column and add the selected value to the current row
    index = values.index(session_state.row[col]) if session_state.row[col] in values else 0

    session_state.row[col] = st.selectbox(col, values, key=col, index=index)

# Add a button to add a new empty row to the dataframe and clear the values of the selectboxes for the current row
if st.button("Add Row"):
    session_state.df = session_state.df.append(session_state.row, ignore_index=True)
    session_state.row = pd.Series(index=columns)

# Display the resulting dataframe
1 Like