diff options
author | Pieter <pmvz_github@outlook.com> | 2023-02-06 21:10:14 +0100 |
---|---|---|
committer | GitHub <noreply@github.com> | 2023-02-06 21:10:14 +0100 |
commit | c6c9f311479666e179ca7877eb47af5a33bf7f38 (patch) | |
tree | 060cb1771b40e006373b198481cef741a1996767 /doc | |
parent | d291e5ef6e24722530ddbe1445a58288c9b473c3 (diff) | |
download | numpy-c6c9f311479666e179ca7877eb47af5a33bf7f38.tar.gz |
DOC: Add N-dimensional argmax/argmin example
Diffstat (limited to 'doc')
-rw-r--r-- | doc/source/user/how-to-index.rst | 20 |
1 files changed, 19 insertions, 1 deletions
diff --git a/doc/source/user/how-to-index.rst b/doc/source/user/how-to-index.rst index e47e9a204..318ac515d 100644 --- a/doc/source/user/how-to-index.rst +++ b/doc/source/user/how-to-index.rst @@ -309,6 +309,24 @@ result as dimensions with size one:: array([[[2, 2, 2, 2, 2]], <BLANKLINE> [[2, 2, 2, 2, 2]]]) + +To get the indices of each maximum or minimum value for each (N-1)-dimensional array in an N-dimensional array, use :meth:`reshape` to reshape the array to a 2D array, apply argmax or argmin along ``axis=1`` and use :meth:`unravel_index` to recover the index of the values per slice:: + + >>> x = np.arange(2*2*3).reshape(2,2,3) % 7 # 3D example array + >>> x + array([[[0, 1, 2], + [3, 4, 5]], + <BLANKLINE> + [[6, 0, 1], + [2, 3, 4]]]) + >>> x_2d = np.reshape(x, (x.shape[0], -1)) + >>> indices_2d = np.argmax(x_2d, axis=1) + >>> indices_2d + array([5, 0]) + >>> np.unravel_index(indices_2d, x.shape[1:]) + (array([1, 0]), array([2, 0])) + +The first array returned contains the indices along axis 1 in the original array, the second array contains the indices along axis 2. The highest value in ``x[0]`` is therefore ``x[0,1,2]``. Index the same ndarray multiple times efficiently ================================================= @@ -348,4 +366,4 @@ Exercises `6`_, `8`_, `10`_, `15`_, `16`_, `19`_, `20`_, `45`_, `59`_, .. _87: https://github.com/rougier/numpy-100/blob/master/100_Numpy_exercises_with_solutions.md#87-consider-a-16x16-array-how-to-get-the-block-sum-block-size-is-4x4- .. _90: https://github.com/rougier/numpy-100/blob/master/100_Numpy_exercises_with_solutions.md#90-given-an-arbitrary-number-of-vectors-build-the-cartesian-product-every-combinations-of-every-item- .. _93: https://github.com/rougier/numpy-100/blob/master/100_Numpy_exercises_with_solutions.md#93-consider-two-arrays-a-and-b-of-shape-83-and-22-how-to-find-rows-of-a-that-contain-elements-of-each-row-of-b-regardless-of-the-order-of-the-elements-in-b- -.. _94: https://github.com/rougier/numpy-100/blob/master/100_Numpy_exercises_with_solutions.md#94-considering-a-10x3-matrix-extract-rows-with-unequal-values-eg-223-
\ No newline at end of file +.. _94: https://github.com/rougier/numpy-100/blob/master/100_Numpy_exercises_with_solutions.md#94-considering-a-10x3-matrix-extract-rows-with-unequal-values-eg-223- |