首页  >  文章  >  后端开发  >  如何使用低维数组有效访问多维数组中的值?

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

Barbara Streisand
Barbara Streisand原创
2024-10-21 13:34:02282浏览

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

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