Reputation: 1521
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
Upvotes: 2
Views: 305
Reputation: 1942
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]
Upvotes: -1
Reputation: 71570
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.
Upvotes: 2
Reputation: 926
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
Upvotes: 3