Sep-27-2023, 10:39 PM
(Sep-27-2023, 09:36 PM)deanhystad Wrote: This is shorter, but it is still messy. The less you have to type, the better the code. If you see that you are going to do the same thing over and over, use program tools designed to repeat something over and over, like a loop. Once you get rid of all the extra dataframes, the only difference between filtering by Region and Market are the names of the columns and the prompt in the sidebar. The rest of the code is the same, and easily moved to a loop. In the code below, I put the column name:sidebar prompt information in a dictionary.
# These are the columns we filter by. column name: sidebar prompt. # Could be list of column names if the column names always matched the prompt. filter_columns = { "Region": "Region", "Market": "Market", "State": "State", "Zmogus": "Person", "Daiktas": "Thing", "Weekday": "Day", "Month": "Month", "Surprise": "Surprise", "Shop": "Shop", "Selma": "Family", "Type": "Type", } st.sidebar.header("Choose your filter") # Loop through all the columns df2 = df.copy() for column, prompt in filter_columns.items(): choices = st.sidebar.multiselect(f"Pick your {prompt}", options=sorted(set(df2[column].values))) if choices: df2 = df2[df2[column].isin(choices)]To add, remove, change a sorting column all you need to do is edit the dictionary.
Your code with dictionary is way more pleasing, i will play with it more and try to understand it because if i choose State as an example - it filters everything what is after the State but not whats above it ( market and region ) [ in sidebar selection mode ]
Also im trying to use less df[numbers] - i like naming it like filtered_df etc as its easier for me to track what i have done and what i have defined.
Thank You again for your time and patience