bundles / numpy latest / numpy / apply_along_axis
_ArrayFunctionDispatcher
numpy:apply_along_axis
source: /dev/numpy/build-install/usr/lib/python3.14/site-packages/numpy/lib/_shape_base_impl.py :278
Signature
def apply_along_axis ( func1d , axis , arr , * args , ** kwargs ) Summary
Apply a function to 1-D slices along the given axis.
Extended Summary
Execute func1d(a, *args, **kwargs) where func1d operates on 1-D arrays and a is a 1-D slice of arr along axis.
This is equivalent to (but faster than) the following use of ndindex and s_, which sets each of ii, jj, and kk to a tuple of indices
Ni, Nk = a.shape[:axis], a.shape[axis+1:] for ii in ndindex(Ni): for kk in ndindex(Nk): f = func1d(arr[ii + s_[:,] + kk]) Nj = f.shape for jj in ndindex(Nj): out[ii + jj + kk] = f[jj]
Equivalently, eliminating the inner loop, this can be expressed as
Ni, Nk = a.shape[:axis], a.shape[axis+1:] for ii in ndindex(Ni): for kk in ndindex(Nk): out[ii + s_[...,] + kk] = func1d(arr[ii + s_[:,] + kk])
Parameters
func1d: function (M,) -> (Nj...)This function should accept 1-D arrays. It is applied to 1-D slices of
arralong the specified axis.axis: integerAxis along which
arris sliced.arr: ndarray (Ni..., M, Nk...)Input array.
args: anyAdditional arguments to
func1d.kwargs: anyAdditional named arguments to
func1d.
Returns
out: ndarray (Ni..., Nj..., Nk...)The output array. The shape of out is identical to the shape of
arr, except along theaxisdimension. This axis is removed, and replaced with new dimensions equal to the shape of the return value offunc1d. So iffunc1dreturns a scalar out will have one fewer dimensions thanarr.
Examples
import numpy as np def my_func(a): """Average first and last element of a 1-D array""" return (a[0] + a[-1]) * 0.5 b = np.array([[1,2,3], [4,5,6], [7,8,9]]) np.apply_along_axis(my_func, 0, b)✓
np.apply_along_axis(my_func, 1, b)
✗b = np.array([[8,1,7], [4,3,9], [5,2,6]]) np.apply_along_axis(sorted, 1, b)✓
b = np.array([[1,2,3], [4,5,6], [7,8,9]])
✓np.apply_along_axis(np.diag, -1, b)
✗See also
- apply_over_axes
Apply a function repeatedly over multiple axes.
Aliases
-
numpy.apply_along_axis