Numpy apply_over_axes: Everything You Need to Know

The difference between axes and axis is, axes are a plural form, and an axis is a singular form. This means, in this function, we can mention axes on which we want to perform our operation.

Numpy apply_over_axes

The np.apply_over_axes() is a built-in Numpy library function used to perform any function over multiple axes in an nd-array repeatedly. The apply_over_axes() method applies the function frequently over multiple axes in an array.

Syntax

numpy.apply_along_axis(1d_func, array, axes, *args, **kwargs)

Parameters

The NumPy apply_over_axes() function have 5 parameters:

  1. 1d_func: This parameter is required to operate the 1D array. It can be applied in the 1D slices of an input array and along the particular axis.
  2. array: This is an array on which we want to work.
  3. axis: These are the required axes along which we want to operate.
  4. *args: This is the additional argument to 1D function (1d_func).
  5. **kwargs: Additional named argument to 1D function (1d_func).

Return Value

The NumPy apply_over_axes() function returns an output array. The shape of the output array can differ depending on whether the function (1d_func) changes the shape of its output as per its input.

Calculate the sum of 2D-array

See the following code.

#Importing numpy
import numpy as np

#We will create a 2D array
#Of shape 4x3
arr = np.array([(1, 10, 3), (14, 5, 6), (7, 8, 19), (50, 51, 52)])
#Printing the array
print("The array is: ")
print(arr)

#Declaring axes
axes = [1, -1]
print("Sum of array elements are:")
print(np.apply_over_axes(np.sum, arr, axes))

Output

The array is:
[[ 1 10  3]
 [14  5  6]
 [ 7  8 19]
 [50 51 52]]
Sum of array elements are:
[[ 14]
 [ 25]
 [ 34]
 [153]]

Explanation

In this example, we have declared one 2D array of size 4×3, we have printed it and its shape.

We have declared axes=[1,-1] and called apply_over_axes() to calculate the sum of its elements. We can see that we have got a column of 4rows; each column has the sum of its row elements.

Calculate the sum of the 3D array

See the following code.

#Importing numpy
import numpy as np

#We will create a 2D array
#Of shape 4x3
arr = np.arange(12).reshape(2, 2, 3)
#Printing the array
print("The array is: ")
print(arr)

#Declaring axes
axes = [0, 2]
print("Sum of array elements are:")
print(np.apply_over_axes(np.sum, arr, axes))

Output

The array is:
[[[ 0  1  2]
  [ 3  4  5]]

 [[ 6  7  8]
  [ 9 10 11]]]
Sum of array elements are:
[[[24]
  [42]]]

Explanation

In this example, we have first declared one 3D array of shapes (2x2x3), and we have printed that array.

We have declared axes with values [0,2], calculating the sum over axes 0 and 2.

We can see that we have the desired output when we have called the function.

See also

NumPy argmax()

NumPy take()

NumPy any()

NumPy all()

NumPy apply_along_axis()

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.