python Streamlit多重选择无法正常执行

ppcbkaq5  于 2023-04-19  发布在  Python
关注(0)|答案(1)|浏览(263)

我写的代码如下streamlit应用程序.我读 Dataframe ,这是其他功能的输出.代码的工作方式,我可以选择项目在多选,然而,当我选择项目在多选,它运行,不更新 Dataframe .我应该如何解决这个问题?

#CODE is the dataframe columns that I perform filtering.
def do_something():

    return df  

df = do_something()

def select(df):

    x= df.CODE.unique().tolist()
    codes= st.columns([0.1, 0.1])

    codes = codes.multiselect("Select Code", x, key={"key1"})

    if codes:
        df = df.query("CODE in @codes)

    return df

版本2:更新代码:

def load_data(id):

do someting
     return dataframes_list,index_dt, s2_dt,start_dt,end_dt 

checkbox_names = ["df1","df2",..]

def create_checkboxes (checkbox_names:List[str],df_list):
    
    checkboxes = {}
    dfs = []
    for name in checkbox_names:
        checkboxes[name] = st.sidebar.checkbox(name, key=name, value=True)
    for key, value in checkboxes.items():
        if st.session_state[key]:
            dfs.append(df_list[list(checkboxes).index(key)])
        
    if len(dfs) > 1:
        df = pd.concat(dfs)
    elif len(dfs) == 1:
        df = dfs[0]
    else:
        st.write("You did not select any dataframes")

    return df 

def timeslider(df):
    cols1, _ = st.columns((5, 1))  # To make it narrower
    format = "MMM DD,YYYY"  # format output

    slider = cols1.slider(
        "Select date",
        key="slider",
        min_value=start_dt,
        value=[start_dt, s2_dt],
        max_value=end_dt,
        format=format,
    )
    minval, maxval = slider
    df = df[(df["DATE"] > minval) & (df["DATE"] < maxval)]
    return df 

def multiselect(df):
    
    code_ = df.CODE.unique().tolist()
    type_ = df.TYPE.unique().tolist()
    codes, types = st.columns([0.1, 0.1])
    codes = codes.multiselect("Select Code", code_, key={"key1"})
    types = types.multiselect("Select Type", type_, key={"key2"})
    if codes or types:
        df = df.query("CODE in @codes or TYPE in @types")

    return df

    dataframes_list,s2_dt,start_dt,end_dt= load_data(id)

    df = create_checkboxes(checkbox_names,dataframes_list)  
    st.write("BEFORE1:")
    st.write(df)
    df = timeslider(df)
    st.write("BEFORE2:")
    st.write(df)
    df = multiselect(df)
    st.write("AFTER:")
    st.write(df)
x4shl7ld

x4shl7ld1#

看起来你只需要在调用select之后/调用select时 * 重新分配 * 你的DataFrame。

import streamlit as st
import pandas as pd

def do_something():
    df = pd.DataFrame({"CODE": ["A", "B", "C", "D", "E"],
                       "VALUE": [1, 2, 3, 4, 5]})
    return df

def select(df):
    x = df.CODE.unique().tolist()
    codes = st.multiselect("Select Code", x, key="key1")

    if codes:
        df = df.query("CODE in @codes")

    return df

df = do_something()
st.write("BEFORE:")
st.write(df)

df = select(df) # <---- add this line
st.write("AFTER:")
st.write(df)

输出:

相关问题