How to replace the existing dataframe by filtered one

I have a streamlit application that read excel file and display the data as dataframe then allow user to do some filter in order to display the required data.

The problem is that i want to display by default all the dataframe then when user make some filter replace the exist datafarme with the filtered dataframe.

The displayed result : empty datafarme

The expected result : By default all record then once the user make the filter it replace the existing dataframe with the filtered datafarme

code:

options_Users = df6['User'].unique().tolist()
selected_Users = st.sidebar.multiselect('Search By User',options_Users)

options_company = df6['company'].unique().tolist()
selected_company = st.sidebar.multiselect('Search By company',options_company)


if selected_Users:
     df6 = df6[df6["User"].isin(selected_Users)]
     st.markdown(
               f'<p class="header_title"> {str(df6.shape[0])} </p>',
               unsafe_allow_html=True,
               )

elif options_company:
     df6 = df6[df6["company"].isin(selected_company)]
     st.markdown(
               f'<p class="header_title"> {str(df6.shape[0])} </p>',
               unsafe_allow_html=True,
               )

else:
     st.markdown(
              f'<p class="header_title"> {str(df6.shape[0])} </p>',
              unsafe_allow_html=True,
          )
st.dataframe(df6.reset_index(drop = True).style.apply(highlight_rows, axis=1))

The problem is the IF statement logic, when the first statement is true the second doesn’t run, and when the second is true you are running the code against the original table instead of the filtered table. Below you will find a sample code that would allow you to filter for the two groups, I tried to keep the same names you had in the original post.

d = {‘User’: [1, 2,3,3], ‘company’: [3, 4,5,3]}
df6 = pd.DataFrame(data=d)

options_Users = df6[‘User’].unique().tolist()
selected_Users = st.sidebar.multiselect(‘Search By User’,options_Users)

options_company = df6[‘company’].unique().tolist()
selected_company = st.sidebar.multiselect(‘Search By company’,options_company)

if selected_Users and not selected_company:
df6 = df6[df6[“User”].isin(selected_Users)]
elif not selected_Users and selected_company:
df6 = df6[df6[“company”].isin(selected_company)]
elif selected_Users and selected_company:
df6 = df6[df6[“User”].isin(selected_Users)]
df6 = df6[df6[“company”].isin(selected_company)]
else:
st.write(‘Please make a valid selection’)

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.