简体   繁体   中英

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. And anyway, attribute access doesn't work like that, but you can use getattr , something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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