基于字符串应用numpy函数

doo*_*oms 3 python numpy

是否可以基于字符串应用 numpy 函数?如果我给 'max' 调用 np.max。

values = np.array([[1,2,-1],[2,3,6], [0,-1,4]]) 
aggregator = 'max'
print np.max(values, axis=0)
>>> [2 3 6]
Run Code Online (Sandbox Code Playgroud)

我希望是这样的:

some_cool_function(aggregator, values, axis=0)
>>> [2 3 6]
Run Code Online (Sandbox Code Playgroud)

这将提供更好的可读性并缩短我的代码。而不是做多个if。

编辑

我找到了numpy.apply_along_axis但它需要一个函数,它不能是一个字符串。

are*_*lek 5

我认为您正在寻找getattr

>>> getattr(np, 'max')(values, axis=0)
array([2, 3, 6])
Run Code Online (Sandbox Code Playgroud)