NumPy Functional programming: apply_over_axes() function
numpy.apply_over_axes() function
The apply_over_axes() function is used to apply a function repeatedly over multiple axes.
func is called as res = func(a, axis), where axis is the first element of axes.
The result res of the function call must have either the same dimensions as a or one less dimension.
If res has one less dimension than a, a dimension is inserted before axis.
The call to func is then repeated for each axis in axes, with res as the first argument.
Syntax:
numpy.apply_over_axes(func, a, axes)
Version: 1.15.0
Parameter:
Name | Description | Required / Optional |
---|---|---|
func | This function must take two arguments, func(a, axis). function |
Required |
a | Input array. array_like |
Required |
axes | Axes over which func is applied; the elements must be integers. array_like |
Required |
Returns: apply_over_axis : ndarray
The output array. The number of dimensions is the same as a, but the shape can be different.
This depends on whether func changes the shape of its output with respect to its input.
Notes:
This function is equivalent to tuple axis arguments to reorderable ufuncs with keepdims=True.
NumPy.apply_over_axes() method Example:
>>> import numpy as np
>>> x = np.arange(24).reshape(3,2,4)
>>> x
Output:
array([[[ 0, 1, 2, 3], [ 4, 5, 6, 7]], [[ 8, 9, 10, 11], [12, 13, 14, 15]], [[16, 17, 18, 19], [20, 21, 22, 23]]])
Sum over axes 0 and 2. The result has same number of dimensions as the original array:
>>> import numpy as np
>>> x = np.arange(24).reshape(3,2,4)
>>> np.apply_over_axes(np.sum, x, [0,2])
Output:
array([[[114], [162]]])
Tuple axis arguments to ufuncs are equivalent:
>>> import numpy as np
>>> x = np.arange(24).reshape(3,2,4)
>>> np.sum(x, axis=(0,2), keepdims=True)
Output:
array([[[114], [162]]])
Python - NumPy Code Editor:
Previous: apply_along_axis() function
Next: vectorize() function
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/numpy/functional-programming/apply_over_axes.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics