Take values from the input array by matching 1d index and data slices. 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 re
(arr, indices, axis=-1)
| 59 | |
| 60 | @array_function_dispatch(_take_along_axis_dispatcher) |
| 61 | def take_along_axis(arr, indices, axis=-1): |
| 62 | """ |
| 63 | Take values from the input array by matching 1d index and data slices. |
| 64 | |
| 65 | This iterates over matching 1d slices oriented along the specified axis in |
| 66 | the index and data arrays, and uses the former to look up values in the |
| 67 | latter. These slices can be different lengths. |
| 68 | |
| 69 | Functions returning an index along an axis, like `argsort` and |
| 70 | `argpartition`, produce suitable indices for this function. |
| 71 | |
| 72 | Parameters |
| 73 | ---------- |
| 74 | arr : ndarray (Ni..., M, Nk...) |
| 75 | Source array |
| 76 | indices : ndarray (Ni..., J, Nk...) |
| 77 | Indices to take along each 1d slice of ``arr``. This must match the |
| 78 | dimension of ``arr``, but dimensions Ni and Nj only need to broadcast |
| 79 | against ``arr``. |
| 80 | axis : int or None, optional |
| 81 | The axis to take 1d slices along. If axis is None, the input array is |
| 82 | treated as if it had first been flattened to 1d, for consistency with |
| 83 | `sort` and `argsort`. |
| 84 | |
| 85 | .. versionchanged:: 2.3 |
| 86 | The default value is now ``-1``. |
| 87 | |
| 88 | Returns |
| 89 | ------- |
| 90 | out: ndarray (Ni..., J, Nk...) |
| 91 | The indexed result. |
| 92 | |
| 93 | Notes |
| 94 | ----- |
| 95 | This is equivalent to (but faster than) the following use of `ndindex` and |
| 96 | `s_`, which sets each of ``ii`` and ``kk`` to a tuple of indices:: |
| 97 | |
| 98 | Ni, M, Nk = a.shape[:axis], a.shape[axis], a.shape[axis+1:] |
| 99 | J = indices.shape[axis] # Need not equal M |
| 100 | out = np.empty(Ni + (J,) + Nk) |
| 101 | |
| 102 | for ii in ndindex(Ni): |
| 103 | for kk in ndindex(Nk): |
| 104 | a_1d = a [ii + s_[:,] + kk] |
| 105 | indices_1d = indices[ii + s_[:,] + kk] |
| 106 | out_1d = out [ii + s_[:,] + kk] |
| 107 | for j in range(J): |
| 108 | out_1d[j] = a_1d[indices_1d[j]] |
| 109 | |
| 110 | Equivalently, eliminating the inner loop, the last two lines would be:: |
| 111 | |
| 112 | out_1d[:] = a_1d[indices_1d] |
| 113 | |
| 114 | See Also |
| 115 | -------- |
| 116 | take : Take along an axis, using the same indices for every 1d slice |
| 117 | put_along_axis : |
| 118 | Put values into the destination array by matching 1d index and data slices |
searching dependent graphs…