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

<pre><code>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
</code></pre>

<p>'mean()' or 'sum()' or whatever ...
like </p>

<pre><code>df.rolling(2).sum()
</code></pre>

<p>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:</p>

<pre><code>def head(x,k = 3):
    return x.head(k)
</code></pre>

<p>What function in python help me to use method like argument in a function?</p>

<pre><code>#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
</code></pre>

<p>You can use <a href="https://docs.python.org/3.6/library/functions.html#getattr" rel="nofollow"><code>getattr</code></a> with a str of the name of the method. This gets the attribute with that name from the object (In this case, a method)</p>

<pre><code>def rolling (df, prefix='r', window=3, method='sum'):
    for name in df.columns:
        df[prefix + name] = getattr(df[name].rolling(window), method)()
    return df
</code></pre>

<p>Or you could just pass in the method. When calling it, the first argument will be <code>self</code>.</p>

<pre><code>def rolling (df, prefix='r', window=3, method=DataReader.sum):
    for name in df.columns:
        df[prefix + name] = method(df[name].rolling(window))
    return df
</code></pre>

python function pandas methods