Python

Numpy Np.Apply_Along_Axis

The apply_along_axis() function is used to apply a specific function to a 1D slice along a specified axis.

Function Syntax

The function syntax is as shown:

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

The parameters are as shown:

  1. func1d – specifies the function that operates on the 1-D slices.
  2. axis – specifies along which axis the array is sliced.
  3. arr – refers to the input array.

The function returns an output array except along the axis. The axis is removed and replaced with the dimensions equal to the shape of the function return value.

 Example

To apply the mean function along the zero axis of a one-dimensional array, we can do:

1
2
3
4
5
6
# import numpy
import numpy as np
def m(a):
   return np.mean(a)
arr = np.array([10,20,20,230,23,243])
print(np.apply_along_axis(m, 0, arr))

This should calculate and return the mean of elements in the input array along the specified axis.

An example return value is as shown:

1
2
Output:
91.0

Example 2

The example below shows how function behaves in a two-dimensional array.

1
2
arr = np.array([[10,20,20],[230,23,243]])
print(np.apply_along_axis(m, 0, arr))

This should return:

1
[120.   21.5 131.5]

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list