Listado de la etiqueta: NpApplyAlongAxis

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:


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.


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


# 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:

Example 2

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


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

This should return:

Source link