what does numpy.apply_along_axis perform exactly?

apply_along_axis applies the supplied function along 1D slices of the input array, with the slices taken along the axis you specify. So in your example, new_func is applied over each slice of the array along the first axis. It becomes clearer if you use a vector valued function, rather than a scalar, like this:

In [20]: b = np.array([[1,2,3], [4,5,6], [7,8,9]])

In [21]: np.apply_along_axis(np.diff,0,b)
Out[21]: 
array([[3, 3, 3],
       [3, 3, 3]])

In [22]: np.apply_along_axis(np.diff,1,b)
Out[22]: 
array([[1, 1],
       [1, 1],
       [1, 1]])

Here, numpy.diff (i.e. the arithmetic difference of adjacent array elements) is applied along each slice of either the first or second axis (dimension) of the input array.


The function is performed on 1-d arrays along axis=0. You can specify another axis using the "axis" argument. A usage of this paradigm is:

np.apply_along_axis(np.cumsum, 0, b)

The function was performed on each subarray along dimension 0. So, it is meant for 1-D functions and returns a 1D array for each 1-D input.

Another example is :

np.apply_along_axis(np.sum, 0, b)

Provides a scalar output for a 1-D array. Of course you could just set the axis parameter in cumsum or sum to do the above, but the point here is that it can be used for any 1-D function you write.