2

If there a way that I can define filter in a variable, then use that variable to filter data frame or filter list?

For example, I can filter the list using code:

l = [1,2,3,4,5]
f = [i for i in l if i > 3]
f

Is there a way that I can define the filter in a variable? (the code below is not working)

ft = repr('if i > 3')
f_repr = [i for i in l eval(ft)] 
f_repr
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Gavin
  • 1,411
  • 5
  • 18
  • 31
  • In pandas, there is a similar filter for data frames [`query`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.query.html). – Space Impact Oct 29 '18 at 04:08
  • 1
    Does it have to be a string? What about something like `condition = lambda i: i > 3` such that you can write `[i for i in l if condition(i)]` or `list(filter(condition, l))`? – timgeb Oct 29 '18 at 04:12

4 Answers4

3

You can do that using a lambda function.

ft=lambda i:i>3
f_repr=[i for i in l if ft(i)]
f_repr
2

You only can do something like:

cond = lambda i: i> 3

Then:

f = [i for i in l if cond(i)]

Or:

f = list(filter(cond, l))

Or for pandas, you can.

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
0

Using numpy arrays is quite straightforward

f_repr = f[f>3]
b-fg
  • 3,959
  • 2
  • 28
  • 44
-1

Make the entire expression a string then eval it.

l = [1,2,3,4,5]
cond = 'if i > 3'
expr = f'[i for i in l {cond}]'
eval(expr) # => [4, 5]
Gabriel
  • 1,922
  • 2
  • 19
  • 37
  • `eval` is not safe, instead it's bad practice https://stackoverflow.com/questions/1832940/why-is-using-eval-a-bad-practice – U13-Forward Oct 29 '18 at 04:32