根据传递给函数的变量选择 pandas 函数
Choosing pandas function based on variable passed to a function
我有以下要概括的代码:
def Fn():
gt75 = itemConst.groupby(['val1', 'val2'])['cumImpa'].shift(fill_value=0).gt(0.75)]
但是我的用法可能非常多样,我最终可能会使用 lt
或 le
等
是否可以有一个泛化函数如下:
def Fn(funcIn):
gt75 = itemConst.groupby(['val1', 'val2'])['cumImpa'].shift(fill_value=0).funcIn(0.75)]
如果您可以提供字符串形式的函数名称,则可以使用 getattr
。 getattr
returns 对象的属性名称。
像这样:
def Fn(funcIn):
foo = itemConst.groupby(['val1', 'val2'])['cumImpa'].shift(fill_value=0)
gt75 = getattr(foo, funcIn)(0.75)
然后称其为Fn('gt')
等
你可以试试:
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)
我有以下要概括的代码:
def Fn():
gt75 = itemConst.groupby(['val1', 'val2'])['cumImpa'].shift(fill_value=0).gt(0.75)]
但是我的用法可能非常多样,我最终可能会使用 lt
或 le
等
是否可以有一个泛化函数如下:
def Fn(funcIn):
gt75 = itemConst.groupby(['val1', 'val2'])['cumImpa'].shift(fill_value=0).funcIn(0.75)]
如果您可以提供字符串形式的函数名称,则可以使用 getattr
。 getattr
returns 对象的属性名称。
像这样:
def Fn(funcIn):
foo = itemConst.groupby(['val1', 'val2'])['cumImpa'].shift(fill_value=0)
gt75 = getattr(foo, funcIn)(0.75)
然后称其为Fn('gt')
等
你可以试试:
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)