4

Is it possible to apply a numpy function based on a string ? If I give 'max' call 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]

What I hope is something like this :

some_cool_function(aggregator, values, axis=0)
>>> [2 3 6]

This will give a better readability and shorten my code. Instead of doing multiple if.

EDIT :

I found the numpy.apply_along_axis but it expects a function, it can't be a string.

dooms
  • 1,537
  • 3
  • 16
  • 30

2 Answers2

7

I think you are looking for getattr:

>>> getattr(np, 'max')(values, axis=0)
array([2, 3, 6])
Community
  • 1
  • 1
arekolek
  • 9,128
  • 3
  • 58
  • 79
0

You can try np.apply_along_axis(). Examples:

>>> np.apply_along_axis(np.max, 0, values)
array([2, 3, 6])

>>> np.apply_along_axis(np.min, 1, values)
array([-1,  2, -1])

EDIT:
If you really want to use strings, you can just make a dictionary mapping your strings to functions (e.g. {'max':np.max, 'min':np.min}) and then wrap the whole thing in a two line super_cool_function.

Gustavo Bezerra
  • 9,984
  • 4
  • 40
  • 48