NumPy apply_along_axis()

The apply_along_axis() method allows you to apply a function to each row or column of a multidimensional array, without using explicit loops.


apply_along_axis() Syntax

The syntax of apply_along_axis() is:

numpy.apply_along_axis(func1d, axis, arr, *args, **kwargs)

apply_along_axis() Arguments

The apply_along_axis() method takes following arguments:

  • func1d - the function to apply along the specified axis
  • axis - the axis along which the function is applied
  • arr - the input array to which the function will be applied
  • *args and **kwargs - additional arguments and keyword arguments present in func1d

Note: The func1d should take a 1D array as input and return a single value or an array of values.

apply_along_axis() Return Value

The apply_along_axis() method returns the resultant array with functions applied.


Example 1: Apply a Function That Returns a Single Value

Output

[3 6 9]
[7 8 9]

Example 2: Apply a Function That Returns an Array of Values

We can also return an array of values from the function.

Output

[[ 1  4  9]
 [16 25 36]
 [49 64 81]]

Example 3: Apply a Function That Returns an N-D Array of Values

We can return an n-D array of values from the function.

Let's see an example.

Output

Along axis 0
[[[  1   4   9]
  [ 16  25  36]
  [ 49  64  81]]

 [[  1   8  27]
  [ 64 125 216]
  [343 512 729]]]

Along axis 1
 [[[  1   4   9]
  [  1   8  27]]

 [[ 16  25  36]
  [ 64 125 216]]

 [[ 49  64  81]
  [343 512 729]]]

For a function that returns a higher dimensional array, the dimensions are inserted in place of the axis dimension.


Example 4: Apply a lambda Function to an Array

Instead of defining a function, we can directly pass a lambda function.

Let's see an example.

Output

[ 6 15 24]

Recommended Reading

Numpy apply_over_axes()