Oleksi Tkachenko Oleksi Tkachenko - 1 year ago 117
Python Question

Method like argument in function

I want use method in python / pandas like argument in a function.
For example rolling statistics for dataframe:

def rolling (df, prefix = 'r', window = 3, method = 'here I wanna choose a method' ):
for name in df.columns:
df[prefix + name] = df[name].rolling(window).'here this method been called'
return df

'mean()' or 'sum()' or whatever ...


I worked 95% time in R, and in R it's simple (put function as an argument or return any function ). But in python I noob. So I creating package to make things easier for me. Like:

def head(x,k = 3):
return x.head(k)

What function in python help me to use method like argument in a function?

#some data
import numpy as np
import pandas as pd
from pandas_datareader.data import DataReader
from datetime import datetime
ibm = DataReader('IBM', 'yahoo', datetime(2000,1,1), datetime(2016,1,1))

ibm2 = rolling(ibm,'rr', 5, 'sum') # something like this

Answer Source

I do this

def rolling (df, prefix='r', window=3, method='method_name'):
    for name in df.columns:
        df[prefix + name] = df[name].rolling(window).__getattribute__(method)()
    return df
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download