-1

I am defining a function where one parameter should be a comparison operator.

I have tried different versions of transforming commands such as float and input

Code I am trying:

def factor_test(factor1, factor2, criteria1, text, criteria2):
    bool_mask1 = rnt2[factor1].str.contains(criteria1,na=False)
    bool_mask2 = rnt2[factor2] criteria2
    # Returns values that are TRUE i.e. an error, not an Boolean dataframe but actual values
    test_name = rnt2[(bool_mask1) & (bool_mask2)] 

criteria2 should be > 0.75:

bool_mask2 = rnt2[factor2] > 0.75

Preferred would be one parameter where I can put in both the > and 0.75, the function should be used about 15 times, with !=, == and <.

Georgy
  • 12,464
  • 7
  • 65
  • 73
uhrskov91
  • 13
  • 2
  • 1
    `lambda x: x > 0.75`? – jonrsharpe Jul 09 '19 at 12:26
  • Very much related but not exact duplicate: [How to pass an 'if' statement to a function?](https://stackoverflow.com/questions/6665082/how-to-pass-an-if-statement-to-a-function) – Georgy Jul 09 '19 at 15:53

2 Answers2

1

Use the operator module:

def factor_test(factor1, factor2, criteria1, text, criteria2, op):
    bool_mask1 = rnt2[factor1].str.contains(criteria1,na=False)
    bool_mask2 = op(rnt2[factor2], criteria2)
    test_name = rnt2[(bool_mask1) & (bool_mask2)] 

Then call with different operators:

import operator

factor_test(factor1, factor2, criteria1, text, criteria2, operator.le)  # <=
factor_test(factor1, factor2, criteria1, text, criteria2, operator.eq)  # ==
# etc
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
1

If you want to pass both a comparison operator and its value as one argument you have several options:

  1. Using operator functions and functools.partial:

    import operator
    from functools import partial
    
    # simple example function
    def my_function(condition):
        return condition(1)
    
    two_greater_than = partial(operator.gt, 2)
    my_function(two_greater_than)
    # True
    
  2. Using dunder methods:

    two_greater_than = (2).__gt__
    my_function(two_greater_than)
    # True
    
  3. Using lambda (as in jonrsharpe's comment)

    two_greater_than = lambda x: 2 > x
    my_function(two_greater_than)
    # True
    
  4. Using a function:

    def two_greater_than(x):
        return 2 > x
    
    my_function(two_greater_than)
    # True
    

Applying any of these approaches to your function with several arguments should be trivial.

Georgy
  • 12,464
  • 7
  • 65
  • 73