How to show the filtered dataframe after user select value from a selectbox in streamlit, where each time the user change the value the page is refreshing and display the entire dataframe.
what i want is to display the filtered dataframe.
I tried to initialize an empty dataframe but once the page refresh it display the below error:
IndexError: list index out of range
Traceback:
File "F:\AIenv\lib\site-packages\streamlit\script_runner.py", line 349, in _run_script
exec(code, module.__dict__)
File "f:\AIenv\streamlit\app.py", line 553, in <module>
main()
File "f:\AIenv\streamlit\app.py", line 543, in main
st.session_state["df_result_search"].columns.tolist()[0]
code:
import streamlit as st
import pandas as pd
def update_df(new_df):
return pd.DataFrame(new_df)
def main():
# df_result_search = pd.DataFrame()
# st.session_state.df_result_search = df_result_search
df =pd.DataFrame({
"source_number":
[11199,11328,11287,32345,12342,1232,13456,123244,13456],
"location":
["loc2","loc1-loc3","loc3","loc1","loc2-loc1","loc2","loc3-loc2","loc2","loc1"],
"category":
["cat1","cat2","cat1","cat3","cat3","cat3","cat2","cat3","cat2"],
})
df_result_search = df
st.write(st.session_state)
with st.form(key='Search_form'):
all_columns = df.columns.tolist()
search_term=st.text_input("Enter Search Term")
if 'search_term' not in st.session_state:
st.session_state.search_term = search_term
if st.form_submit_button("search"):
# if len(search_term)>0:
df_result_search = df[df.isin([search_term]).any(axis=1)]
st.session_state.search_term = search_term
if 'df_result_search' not in st.session_state:
st.write("Session Out")
else:
st.write("Session IN")
st.session_state.df_result_search = df_result_search
st.dataframe(st.session_state["df_result_search"])
df_len = range(len(df_result_search.index))
index = df_result_search.columns.tolist().index(
st.session_state["df_result_search"].columns.tolist()[0]
)
st.write("index :{}".format(index))
df_len = range(len(df_result_search.index))
s = st.selectbox('Select index',key="select_box",options=df_len,index = index,on_change=lambda: update_df(df_result_search))
print(st.session_state.select_box)
st.write("values is {}".format(st.session_state.select_box))
if __name__ == '__main__':
main()