I have a python that initialize a dataframe than the user can filter this dataframe based text_input where it display the records related to the user input then the user can select witch record want to update by selecting from the selectbox the index number of the filtered dataframe.
The problem is that once the user select the index number the system crash and 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]
I know that this error appear because i am initializing the df_result_search as empty dataframe
But also i am saving the df_result_search based on the user input by using st.session_state
new feature… but the system seams like doesn’t save the filtered dataframe and when the page refresh it assign the new dataframe as empty.
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"],
})
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"):
df_result_search = df[df.isin([search_term]).any(axis=1)]
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()