Reputation: 4807
I have the following code which I am trying to generalize:
def Fn():
gt75 = itemConst.groupby(['val1', 'val2'])['cumImpa'].shift(fill_value=0).gt(0.75)]
My usage however can be very varied and I might end up using lt
or le
etc.
Is it possible to have a generalized function as follows:
def Fn(funcIn):
gt75 = itemConst.groupby(['val1', 'val2'])['cumImpa'].shift(fill_value=0).funcIn(0.75)]
Upvotes: 0
Views: 24
Reputation: 120429
You could try:
ne = pd.Series.ne # or pd.DataFrame.ne
eq = pd.Series.eq # or pd.DataFrame.eq
le = pd.Series.le # ...
lt = pd.Series.lt # itemConst['cumpImpa'] is a Series
ge = pd.Series.ge
gt = pd.Series.gt
def binop(op, val):
return op(itemConst.groupby(['val1', 'val2'])['cumImpa'].shift(fill_value=0), val)
mask = binop(gt, 0.75)
Upvotes: 2
Reputation: 3856
If you can provide the function name as a string, you can use getattr
. getattr
returns an attribute of an object by name.
Something like this:
def Fn(funcIn):
foo = itemConst.groupby(['val1', 'val2'])['cumImpa'].shift(fill_value=0)
gt75 = getattr(foo, funcIn)(0.75)
And then call it as Fn('gt')
etc.
Upvotes: 1