简体   繁体   English

在python中将函数作为参数传递

[英]Passing Function as parameter in python

I am trying to make a function to calculate rolling mean or sum :我正在尝试创建一个函数来计算滚动平均值或总和:

def rolling_lag_creator(dataset,i,func):  
    dataset['Bid']=dataset.loc[:,'Bid'].rolling(window=i).func()
    return dataset

but this function is throwing error when i am calling this:但是当我调用这个函数时,这个函数抛出错误:

rolling_lag_creator(Hypothesis_ADS,5,mean)

Error:错误:

NameError: name 'mean' is not defined

while below code works fine:虽然下面的代码工作正常:

dataset['Bid']=dataset.loc[:,'Bid'].rolling(window=5).mean()

Can anyone help me how to call such methods as parameters, thank you.谁能帮我如何调用这样的方法作为参数,谢谢。

mean is a method , not a function per se. mean是一种方法,而不是函数本身。 And anyway, attribute access doesn't work like that, but you can use getattr , something like this:无论如何,属性访问不是这样工作的,但您可以使用getattr ,如下所示:

def rolling_lag_creator(dataset, i, method_name):
    method = getattr(dataset.loc[:,'Bid'].rolling(window=i), method_name)
    dataset['Bid'] = method()
    return dataset

rolling_lag_creator(Hypothesis_ADS, 5, 'mean')

I guess you need to:我想你需要:

import numpy as np

and then replace mean with np.mean然后用np.mean替换mean

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM