flopscope.numpy.put_along_axis
fnp.put_along_axis(arr, indices, values, axis, *args, **kwargs)[flopscope source][numpy source]
Put values into the destination array by matching 1d index and data slices.
Adapted from NumPy docs np.put_along_axis
Put values into destination array using indices. Cost: numel(input).
This iterates over matching 1d slices oriented along the specified axis in the index and data arrays, and uses the former to place values into 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...)
Destination array.
- indices:ndarray (Ni..., J, Nk...)
Indices to change along each 1d slice of
arr. This must match the dimension of arr, but dimensions in Ni and Nj may be 1 to broadcast againstarr.- values:array_like (Ni..., J, Nk...)
values to insert at those indices. Its shape and dimension are broadcast to match that of indices.
- axis:int
The axis to take 1d slices along. If axis is None, the destination array is treated as if a flattened 1d view had been created of it.
See also
- we.flops.take_along_axis Take values from the input array by matching 1d index and data slices
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
for ii in ndindex(Ni):
for kk in ndindex(Nk):
a_1d = a [ii + s_[:,] + kk]
indices_1d = indices[ii + s_[:,] + kk]
values_1d = values [ii + s_[:,] + kk]
for j in range(J):
a_1d[indices_1d[j]] = values_1d[j]Equivalently, eliminating the inner loop, the last two lines would be:
a_1d[indices_1d] = values_1dExamples
>>> import flopscope.numpy as fnpFor this sample array
>>> a = flops.array([[10, 30, 20], [60, 40, 50]])We can replace the maximum values with:
>>> ai = flops.argmax(a, axis=1, keepdims=True)
>>> ai
array([[1],
[0]])
>>> flops.put_along_axis(a, ai, 99, axis=1)
>>> a
array([[10, 99, 20],
[99, 40, 50]])