Updating data in in editable dataframe (st.experimental_data_editor)

Ah, I think I might understand better what you’re looking for. I think having two columns side-by-side is a reasonable solution.

Another way to do it is to update the original dataframe in place by using session state, but I think you’ll find this works better if you explicitly add a button to trigger the rerun.

Here’s a slightly modified script that adds a button to recalculate the values, and calls experimental_rerun to update the whole page.

import pandas as pd
import statsmodels.api as sm
import streamlit as st

st.set_page_config(layout="wide")

st.write("**By: [Bilal Mussa](https://www.linkedin.com/in/bilalmussa/)**")


@st.cache_data
def tidy_data(data):
    # clean up some of the data where needed
    data["date"] = pd.to_datetime(data["date"]).dt.date
    data = data.fillna(0)
    return data


st.sidebar.write("Please load your data in")

user_input = st.sidebar.file_uploader("Upload CSV", type=["csv"])

if user_input is None:
    st.stop()

raw_data = tidy_data(pd.read_csv(user_input, parse_dates=["date"], dayfirst=True))

model_vars = list(raw_data.columns)
model_vars.remove("date")

st.sidebar.write("Please select your dependant variable")

option = st.sidebar.selectbox("Select your dep var?", (model_vars))

st.sidebar.write("You selected:", option)

if "model_specs" not in st.session_state:
    # Now we will create the model spec page/editable dataframe
    model_specs = pd.DataFrame(model_vars, columns=["variable"])
    model_specs["log"] = 0
    model_specs["Adstock"] = 0
    model_specs["DimRet"] = 0
    model_specs["Coef."] = 0
    model_specs["Std.Err."] = 0
    model_specs["t"] = 0
    model_specs["P>|t|"] = 0
    model_specs["Override"] = 1
    model_specs["Fixed"] = 0
    model_specs["DecompGroup"] = ""
    st.session_state["model_specs"] = model_specs

edited_df = st.experimental_data_editor(st.session_state["model_specs"])
if edited_df.index.name != "variable":
    edited_df = edited_df.set_index("variable")

selected_vars = list(edited_df[edited_df["Override"] == 1].index)

y = raw_data[option]
x = raw_data[selected_vars]

model = sm.OLS(y, x).fit()
predictions = model.predict(x)
LRresult = model.summary2().tables[1]
LRresult = LRresult.rename_axis("variable")

# print_model = model.summary()
# st.text(print_model)
# print(print_model)

if st.button("Update values"):
    edited_df.update(LRresult)
    st.session_state["model_specs"] = edited_df
    st.experimental_rerun()
3 Likes