首页  >  文章  >  后端开发  >  如何访问维度较少的多维数组?

如何访问维度较少的多维数组?

Linda Hamilton
Linda Hamilton原创
2024-10-21 11:32:02832浏览

How to Access Multidimensional Arrays with Fewer Dimensions?

访问维度较少的多维数组

考虑一个 n 维数组,例如 a 和 (n-1) 维数组,idx。要沿给定维度使用 idx 访问 a,我们可以采用高级索引。

对于 3 维数组 a,我们可以使用 idx 计算沿第一个维度的最大值,如下所示:

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

这种方法可以推广到任意维数的数组:

<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>

要使用 (n-1) 维数组索引 n 维数组,我们可以创建一个网格所有轴的索引:

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

使用此网格,我们可以索引输入数组:

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

这种方法为访问具有较少维度的多维数组提供了一种优雅的解决方案。

以上是如何访问维度较少的多维数组?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn