Multiple filters based on checkboxes

Hi everyone!
I have five checkboxes. When some of them are selected, I want my dataframe to be filtered on some specific condition. Additionally, values should be filtered with the AND logic. For example:

if filter1 & filter2:
   df = df .loc[(some condition of filter1) & (some condition of filter2)]

However, having five filters, I have to use a lot of different combinations to implement such logic (e.g. if filter1 & filter3, if filter1 & filter4, if filter1 & filter3 & filter4, and so on).

Is there is a more effective way to do it without going through all the filters combinations in if statements?

I checked this solution, however, it is applicable for sliders only as I understand it:

I would highly appreciate any help!

Hi, you could try doing it this way:

  1. Start with a blank string (Eg. querystr = ‘’)
  2. Using your checkboxes, you can incrementally construct your combined filter, appending the result to querystr. (Eg. querystr = querystr + "Gender == ‘M’ "

Gender would be the dataframe field and ‘M’ could be check box value.

Similarly continue with your other checkboxes…

querystr = querystr + "Race == ‘White’ ") will make the resultant query string for Gender as well as Race… And so on…

Finally, you can use df.query

Refer internet help docs as needed.

Hope this helps,

Hi @Shawn_Pereira,
Thank you!
A brilliant solution and clear explanation. However, it’s not possible to simply concatenate strings as pandas.DataFrame.query requires an ‘and’ operator for multiple conditions. Thus, I did the check for each filter as in the next example.

if not querystr == "":
   querystr = querystr + "**and** condition"
else:
   querystr = querystr + "condition"

Otherwise, it fully covered my needs.

Hi @kolazar ,

Then consider this method too:

  1. Start with a blank querystr
  2. Iterate through your check boxes, incrementally adding to the querystr

Eg. querystr = querystr + fieldname + " == " + fieldvalue + " and "

Since your fieldvalue is characters, you will not need to use the str function to join it with querystr.

  1. After processing all your check boxes, check if
    a. querystr is still empty. i.e
    no condition is chosen at all, and
    b. If querystr ends with + " and ". If yes, remove those many characters from the end of the querystr.
  2. If you want to check and manage errors, you can consider using the try-except statements to process the final querystr.

Cheers

Thank you for proposing this alternative approach. I appreciate it a lot!

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