Reputation: 351
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 ... like
df.rolling(2).sum()
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
Upvotes: 1
Views: 106
Reputation: 531165
A method is an attribute like any other (it just happens to be callable when bound to an object), so you can use getattr
. (A default value of None
is nonsense, of course, but I didn't want to reorder your signature to make method
occur earlier without a default value.)
def rolling (df, prefix='r', window=3, method=None):
for name in df.columns:
obj = df[name].rolling(window)
m = getattr(obj, method)
df[prefix + name] = m()
return df
Upvotes: 0
Reputation: 294258
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
Upvotes: 1
Reputation: 40811
You can use getattr
with a str of the name of the method. This gets the attribute with that name from the object (In this case, a method)
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
Or you could just pass in the method. When calling it, the first argument will be self
.
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
Upvotes: 3