bundles / numpy latest / numpy / take_along_axis
_ArrayFunctionDispatcher
numpy:take_along_axis
source: /dev/numpy/build-install/usr/lib/python3.14/site-packages/numpy/lib/_shape_base_impl.py :62
Signature
def take_along_axis ( arr , indices , axis = -1 ) Summary
Take values from the input array by matching 1d index and data slices.
Extended Summary
This iterates over matching 1d slices oriented along the specified axis in the index and data arrays, and uses the former to look up values in the latter. These slices can be different lengths.
Functions returning an index along an axis, like argsort and argpartition, produce suitable indices for this function.
Parameters
arr: ndarray (Ni..., M, Nk...)Source array
indices: ndarray (Ni..., J, Nk...)Indices to take along each 1d slice of
arr. This must match the dimension ofarr, but dimensions Ni and Nj only need to broadcast againstarr.axis: int or None, optionalThe axis to take 1d slices along. If axis is None, the input array is treated as if it had first been flattened to 1d, for consistency with
sortandargsort.
Returns
: out: ndarray (Ni..., J, Nk...)The indexed result.
Notes
This is equivalent to (but faster than) the following use of ndindex and s_, which sets each of ii and kk to a tuple of indices
Ni, M, Nk = a.shape[:axis], a.shape[axis], a.shape[axis+1:] J = indices.shape[axis] # Need not equal M out = np.empty(Ni + (J,) + Nk) for ii in ndindex(Ni): for kk in ndindex(Nk): a_1d = a [ii + s_[:,] + kk] indices_1d = indices[ii + s_[:,] + kk] out_1d = out [ii + s_[:,] + kk] for j in range(J): out_1d[j] = a_1d[indices_1d[j]]
Equivalently, eliminating the inner loop, the last two lines would be
out_1d[:] = a_1d[indices_1d]Examples
import numpy as np
✓a = np.array([[10, 30, 20], [60, 40, 50]])
✓np.sort(a, axis=1) ai = np.argsort(a, axis=1) ai np.take_along_axis(a, ai, axis=1)✓
np.max(a, axis=1, keepdims=True) ai = np.argmax(a, axis=1, keepdims=True) ai np.take_along_axis(a, ai, axis=1)✓
ai_min = np.argmin(a, axis=1, keepdims=True) ai_max = np.argmax(a, axis=1, keepdims=True) ai = np.concatenate([ai_min, ai_max], axis=1) ai np.take_along_axis(a, ai, axis=1)✓
See also
- put_along_axis
Put values into the destination array by matching 1d index and data slices
- take
Take along an axis, using the same indices for every 1d slice
Aliases
-
numpy.take_along_axis