Numpy function apply_along_axis

I am trying to use numpys apply_along_axis with a function that needs more than one argument.

test_array = np.arange(10)
test_array2 = np.arange(10)

def example_func(a,b):
   return a+b

np.apply_along_axis(example_func, axis=0, arr=test_array, args=test_array2)

In the manual: http://docs.scipy.org/doc/numpy/reference/generated/numpy.apply_along_axis.html there is an args parameter for additional parameters. But if I try to add this parameter, python will return an error:

* TypeError: apply_along_axis () received an unexpected keyword argument 'args' *

or if I do not use arguments, the argument is missing

* TypeError: example_func () takes exactly 2 arguments (1 set) *

This is just a sample code, and I know that I can solve it in different ways, for example using numpy.add or np.vectorize. But my question is, can I use the numpys apply_along_axis function with a function that uses multiple arguments.

+4
source share
1 answer

*argsin a signature numpy.apply_along_axis(func1d, axis, arr, *args)means that other positional arguments can be passed .

If you want to add two numpy arrays in different ways, just use the operator +:

In [112]: test_array = np.arange(10)
     ...: test_array2 = np.arange(10)

In [113]: test_array+test_array2
Out[113]: array([ 0,  2,  4,  6,  8, 10, 12, 14, 16, 18])

Remove keywords axis=, arr=, args=and it should work:

In [120]: np.apply_along_axis(example_func, 0, test_array, test_array2)
Out[120]: array([ 0,  2,  4,  6,  8, 10, 12, 14, 16, 18])
+4
source

Source: https://habr.com/ru/post/1527189/


All Articles