update the value of metric in streamlit using session_state

Viewed 86

I have streamlit app where i load a dataframe with the ability to filter and return data based on the user input. I have a function that return the number of returned records using df.shape[0].

What i want is to change the displayed number of records based on the return result by the user filter. so i did use for the st.session_state but it seems i misused.

code:

def metric_employee(df):
    
    if "df" in st.session_state:
        return df['status_type'].value_counts()["employee"]
    st.session_state.df=pd.DataFrame(df,columns= df.columns)
    return st.session_state.df

result = df    
col1_m,col2_m,col3_m = st.columns(3)
    #  use session state to display number corresponding to the result table!!!!!!!!
    with col1_m:
        st.markdown(
            f'<p class = "employee_metric"> {metric_employee(result)} employee</p>',
            unsafe_allow_html= True,
        )

if radioDB=="Search":  
        regular_search_term=st.sidebar.text_input("Enter Search Term")
        if st.sidebar.button("search",key=1):    
            result = df[df['name'].str.contains(regular_search_term)|
            df['nickname'].str.contains(regular_search_term)|
            df['mother_name'].str.contains(regular_search_term)]

            st.write(f"{str(result.shape[0])} Records ")
            display_aggrid(result)

st.write(f"{str(result.shape[0])} Records ")

the statement above display the total returned result what i want in my metric is to display the number of records in column status_type where the cell value is employee , and i want to change this number each time the user filter the dataframe.

so what is my mistake and how to change the number based on the returned results?

1 Answers

Use this.

def metric_employee(df):
    """
    Returns the number of records on column status_type with
    employee value from the given df.
    """
    dfe = df.loc[df['status_type'] == 'employee']
    return len(dfe)
Related