1

I am writing a small web page with streamlit, the user selects variables/criteria from dropdown/slider menu, and a dataframe is then searched by the criteria.

The criteria are in a dict like so:

    dict_choice = {'Site': 'Broadbent',
       'Cover': '53',
       'Weight': (1.9875, 5.9625),
       'SVL': (18.75, 56.25),
       'VTL': (22.25, 66.75),
       'Regen': (16.5, 49.5)}

At this point, I'd like to search the df, something like this:

   newdf = df.loc[(df['Site']==site_choice) &
           (df['Cover']==cover_choice) & 
           ((df['Weight']>=weight_choice[0]) & (df['Weight']<=weight_choice[1])) &
           ((df['VTL']>=vtl_choice[0]) & (df['VTL']<=vtl_choice[1])) &
           ((df['SVL']>=svl_choice[0]) & (df['SVL']<=svl_choice[1])) &
           ((df['Regen']>=regen_choice[0]) & (df['Regen']<=regen_choice[1]))
           ]

How do I iterate over the dictionary to make the search query? My main problem are the criteria which include a range.

I know that if there wasn't a range, I can do:

  results_df = df.loc[df[list(dict_choice.keys())].isin(list(dict_choice.values())).all(axis=1), :]

But no idea how to filter by range. Halp.

queste
  • 188
  • 1
  • 14
  • Does this answer your question? [Pandas: Filtering multiple conditions](https://stackoverflow.com/questions/48978550/pandas-filtering-multiple-conditions) – Kermit Jan 24 '21 at 03:16
  • Just a tip you can write comparisons like `df['Weight']>=weight_choice[0]) & (df['Weight']<=weight_choice[1]` as `weight_choice[0] <= df['Weight'] <= weight_choice[1]` . The second way is more pythonic. – BeanBagTheCat Jan 24 '21 at 03:50
  • Thanks @BeanBagTheCat, that does read better :) – queste Jan 24 '21 at 03:57

0 Answers0