Updating DataFrame Entries Using Streamlit Widgets

I am developing a Streamlit app that allows users to edit entries within a pandas DataFrame. The app should enable users to modify the values of specific DataFrame entries. However, I’m encountering an issue where the values collected for updating the DataFrame do not seem to be properly updated upon user interaction.

What I’ve Tried: I’ve tried capturing the input values within the button click event, expecting that Streamlit would update updated_values based on the latest user input. However, this does not seem to work as expected, and I’m unsure if I’m missing something about how Streamlit handles state or widget interaction.

Minimal Working Example (MWE):

import streamlit as st
import pandas as pd

# Initialize the DataFrame in session_state if it doesn't already exist
if 'df' not in st.session_state:
    # Sample DataFrame
    data = {'custom_id': [1, 2], 'name': ['Alice', 'Bob'], 'age': [30, 25]}
    st.session_state.df = pd.DataFrame(data)

# Function to edit a DataFrame entry
def edit_entry(df, index):
    if index < 0 or index >= len(df):
        st.error("Index out of range")
        return df

    # Display text input for each field except 'custom_id', and store updates in a local dictionary
    updated_values = {col: st.text_input(f"{col} (Index {index})", value=str(df.loc[index, col])) for col in df.columns if col != "custom_id"}

    # Attempt to update the entry on button click
    if st.button("Update Entry"):
        for col, value in updated_values.items():
            df.at[index, col] = value  # Update the DataFrame directly
        st.success("Entry updated successfully.")
    
    return df

# Using the function in the app and updating st.session_state.df with the returned value
index = 0  # Example index for demonstration
st.session_state.df = edit_entry(st.session_state.df, index)

Or maybe there is a much better way to update a dataframe (or a csv file on which it is based)?

Hi @bignoub

Perhaps you can try combining the new entry with the original dataframe using pandas’ pd.concat() method.

Here’s the Docs page with examples and detail
https://pandas.pydata.org/docs/reference/api/pandas.concat.html

Hope this helps!