0

I want to produce a simple filter:

fil = (df['col'] == cond 1) | (df['col'] == cond 2) | (df['col'] == cond 3)

however, the number of conditions varies. So in another case, the filter would look like:

fil = (df['col'] == cond 1) | (df['col'] == cond 2)

or

fil = (df['col'] == cond 1) | (df['col'] == cond 2) | (df['col'] == cond 3) | (df['col'] == cond 4)

The conditions themselves are available as a list, i.e.:

condList = [cond 1, cond 2, cond 3]

or

condList = [cond 1, cond 2]

or

condList = [cond 1, cond 2, cond 3, cond 3]

So I would like to have a filter that would somehow look like:

fil = df['col'] == or(condList)
  • 2
    You can use .isin([list_of_values]) function. https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.isin.html – Gedas Miksenas Jun 08 '22 at 12:52
  • Are the conditions always as you say i.e. always `==` and combined using `|`? – Tom B. Jun 08 '22 at 13:00
  • @Tom actually no. Sometimes it is also e.g., xxx.str.contains(cond 1) | xxx.str.contains(cond 2) – and I am not sure .isin then works (which is great otherwise). – Mockup Dungeon Jun 08 '22 at 13:20
  • I am not sure it is possible then (but someone may prove me wrong). If the conditions used, for example, depended on the length of `condList` then I guess you could call different functions applying the condition depending on `len(condList)`. However without such dependence, I am not sure how you would proceed. – Tom B. Jun 08 '22 at 14:40

0 Answers0