如何使用低维数组有效访问多维数组中的值?

Barbara Streisand
发布: 2024-10-21 13:34:02
原创
297 人浏览过

How to Access Values in Multidimensional Arrays Using Lower- Dimensional Arrays Effectively?

使用低维数组访问多维数组

在多维数组中,使用较低维度的数组沿特定维度检索值可以是具有挑战性的。考虑下面的示例:

<code class="python">a = np.random.random_sample((3,4,4))
b = np.random.random_sample((3,4,4))
idx = np.argmax(a, axis=0)</code>
登录后复制

我们如何使用 idx 访问 a 中的最大值,就像使用 a.max(axis=0) 一样?我们如何从 b 中检索相应的值?

使用高级索引的优雅解决方案

高级索引提供了一种灵活的方法来实现此目的:

<code class="python">m, n = a.shape[1:]  # Extract dimensions excluding axis 0
I, J = np.ogrid[:m, :n]
a_max_values = a[idx, I, J]  # Index using the grid
b_max_values = b[idx, I, J]</code>
登录后复制

该解决方案利用了网格 [idx, I, J] 跨越剩余维度的所有可能的索引组合的事实。

任意维度的泛化

对于一般的n维数组,可以定义一个函数来推广上述解决方案:

<code class="python">def argmax_to_max(arr, argmax, axis):
    """
    Apply argmax() operation along one axis to retrieve maxima.

    Args:
        arr: Array to apply argmax to
        argmax: Resulting argmax array
        axis: Axis to apply argmax (0-based)
    Returns:
        Maximum values along specified axis
    """
    new_shape = list(arr.shape)
    del new_shape[axis]

    grid = np.ogrid[tuple(map(slice, new_shape))]  # Create grid of indices
    grid.insert(axis, argmax)

    return arr[tuple(grid)]</code>
登录后复制

替代索引方法

或者,可以创建一个函数为所有轴生成索引网格:

<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中文网其他相关文章!

来源:php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!