Code
import numpy as np
= np.array([11, 12, np.nan, 14, 15]) A
Python does not have a direct equivalent to R’s do.call
or match.fun
.
However, one can achieve a similar effect using a dictionary to map function names to their actual function objects, as shown in the previous response.
An alternative option is to use partial
function of functools
library.
import numpy as np
= np.array([11, 12, np.nan, 14, 15]) A
def fn_N(x, na_rm=False):
= len(x) - np.isnan(x).sum() if na_rm else len(x)
xn return xn
def fn_sum(x, na_rm=False):
return np.nansum(x) if na_rm else np.sum(x)
def fn_mean(x, na_rm=False):
= fn_N(x, na_rm=na_rm)
xn = fn_sum(x, na_rm=na_rm)
xsum = xsum / xn
xmean return xmean
def fn_call(func_name, *args, **kwargs):
= {
function_map 'fn_mean': fn_mean,
}
= function_map.get(func_name)
func if func is None:
raise ValueError("Function not found")
return func(*args, **kwargs)
'fn_mean', A, na_rm=True) fn_call(
functools
import numpy as np
from functools import partial
def fn_N(x, na_rm=False):
= len(x) - np.isnan(x).sum() if na_rm else len(x)
xn return xn
def fn_sum(x, na_rm=False):
return np.nansum(x) if na_rm else np.sum(x)
def fn_xmean(x, na_rm=False):
= fn_N(x, na_rm=na_rm)
xn = fn_sum(x, na_rm=na_rm)
xsum = xsum / xn
xmean return xmean
# Using functools.partial to create a function with preset arguments
def fn_call(func_name, *args, **kwargs):
= globals().get(func_name)
func if func is None:
raise ValueError("Function not found")
= partial(func, *args, **kwargs)
partial_func return partial_func()
'fn_mean', A, na_rm=True) fn_call(