Zanam Zanam - 2 years ago 98
Python Question

Python: using variable as function name

I aim to create a function wrapper across this statement:

import pandas as pd
import numpy as np
MonthNumber = np.array([1,1,2,4,5,6,5])
Data = np.array([1.1,3,.52,34,15,45,34])
Data2 = Data * 1.1
Data3 = Data * 2
df = pd.DataFrame({'Month':MonthNumber, 'Data':Data})
Summary = pd.pivot_table(df,index=['Month'],values='Data'],aggfunc=[np.sum,np.var])

so that the wrapper function looks like:

def summarywrapper(MonthNumber,Data,**kwargs):
df = pd.DataFrame({'Month':MonthNumber, 'Data':Data})
Summary = pd.pivot_table(df,index=['Month'],values='Data'],aggfunc=[kwar1,kwarg2,etc])
return Summary

**kwargs would contain any number of parameters like mean, len, variance that I want to supply

Also I want to be able to supply any random number of arrays like Data2, Data3 instead of just two arrays like shown in example.

How do I achieve supplying the variable number of arrays to the "SummaryFunction" and variable number of parameters that I want to calculate.

Answer Source

It's unclear what is your input, but in Python functions are first-class objects and may be passed as function argument.

Sample implementation using *args may be following:

def summarywrapper(MonthNumber, Data, *args):
   df = pd.DataFrame({'Month':MonthNumber, 'Data':Data})
   Summary = pd.pivot_table(df,index=['Month'],values='Data'],aggfunc=args)
   return Summary

With sample usage:

summarywrapper(monthNumber, data, np.sum, np.var)

Here, functions itself are passed as variadic arguments.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download