Home >Backend Development >Python Tutorial >How to Access Multidimensional Arrays with Fewer Dimensions?

How to Access Multidimensional Arrays with Fewer Dimensions?

Linda Hamilton
Linda HamiltonOriginal
2024-10-21 11:32:02922browse

How to Access Multidimensional Arrays with Fewer Dimensions?

Accessing Multidimensional Arrays with Fewer Dimensions

Consider an n-dimensional array, such as a, and an (n-1)-dimensional array, idx. To access a using idx along a given dimension, we can employ advanced indexing.

For a 3-dimensional array a, we can calculate the maximum values along the first dimension using idx as follows:

<code class="python">m, n = a.shape[1:]
I, J = np.ogrid[:m, :n]
a_max_values = a[idx, I, J]</code>

This approach can be generalized for arrays with any number of dimensions:

<code class="python">def argmax_to_max(arr, argmax, axis):
    new_shape = list(arr.shape)
    del new_shape[axis]
    grid = np.ogrid[tuple(map(slice, new_shape))]
    grid.insert(axis, argmax)
    return arr[tuple(grid)]</code>

To index an n-dimensional array with an (n-1)-dimensional array, we can create a grid of indices for all axes:

<code class="python">def all_idx(idx, axis):
    grid = np.ogrid[tuple(map(slice, idx.shape))]
    grid.insert(axis, idx)
    return tuple(grid)</code>

Using this grid, we can index into the input arrays:

<code class="python">a_max_values = a[all_idx(idx, axis=axis)]
b_max_values = b[all_idx(idx, axis=axis)]</code>

This approach provides an elegant solution for accessing multidimensional arrays with fewer dimensions.

The above is the detailed content of How to Access Multidimensional Arrays with Fewer Dimensions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn