pandas streamlit仅在使用st.data_editor每秒钟更改一次后更新一次框架

ut6juiuv  于 2023-11-15  发布在  其他
关注(0)|答案(1)|浏览(596)

我试图根据用户在不同列中使用st.data_editor进行的更改来更改列中的值,并希望在更改后实时执行。但以下代码仅在2次更改后有效,并且仅显示初始更改。
代码通过运行streamlit run main.py来运行

main.py

from page import page

page()

字符串

page.py

import streamlit as st
import pandas as pd

boq_df = pd.DataFrame()

def update_dataframe():
    boq_df.loc[boq_df["ANALYZE"] == False, "TYPE"] = None
    boq_df.ffill(inplace=True)

def page():
    global boq_df

    st.write("# Test")

    if st.button("Analyze", type="primary"):
        boq_df = pd.DataFrame(
            data={
                "ANALYZE": [True, False, True],
                "CAT": ["Car", "Truck", "Bike"],
                "TYPE": ["blue", False, "yellow"],
                "DESC": ["two door", "four door", "single"],
            }
        )

    if not boq_df.empty:
        boq_df = st.data_editor(boq_df, height=700, on_change=update_dataframe())

oknwwptz

oknwwptz1#

不要在streamlit中使用全局变量。当用户界面发生变化时,Streamlit总是从上到下重新编译代码。相反,使用内置的会话状态字典。
另外,数据编辑器中的on_change仅在添加或删除行时有用。编辑时,直接使用data_editor的返回值。
我试着修改你的代码。

import streamlit as st
import pandas as pd

# Create a session variable
if 'boq' not in st.session_state:
    st.session_state['boq'] = pd.DataFrame()

def page():
    st.write("# Test")

    # If button is pressed, assign a pre-built dataframe to the variable.
    if st.button("Analyze", type="primary"):
        st.session_state['boq'] = pd.DataFrame(
            data={
                "ANALYZE": [True, False, True],
                "CAT": ["Car", "Truck", "Bike"],
                "TYPE": ["blue", False, "yellow"],
                "DESC": ["two door", "four door", "single"],
            }
        )

    # If variable is not empty, construct a data_editor.
    if not st.session_state['boq'].empty:
        edited_df = st.data_editor(
            st.session_state['boq'],
            height=700
        )

        # If column "ANALYZE" is set to False, set the value of
        # "TYPE" to None. Be sure to update column "TYPE" only if
        # there are changes to column "ANALYZE".
        is_equal = edited_df['ANALYZE'].equals(st.session_state['boq']['ANALYZE'])
        if not is_equal:
            edited_df.loc[edited_df["ANALYZE"] == False, "TYPE"] = None
            edited_df.ffill(inplace=True)
            st.session_state['boq'] = edited_df  # update the variable

            # Set streamlit to rerun the script from top to bottom
            # to update the data editor.
            st.rerun()

page()

字符串


的数据

相关问题