如何使用两个索引列表对 2D NumPy 数组进行索引,以及广播问题的解决方案是什么?

Patricia Arquette
发布: 2024-10-26 15:06:02
原创
761 人浏览过

How can I index a 2D NumPy array using two lists of indices, and what are the solutions to broadcasting issues?

使用 2 个索引列表对 2D Numpy 数组进行索引

在 NumPy 中,有多种方法使用两个索引来索引 2D 数组索引列表,一个用于行,一个用于列。让我们探索这些方法并解决广播问题。

通过索引数组使用广播

要使用两个索引数组 row_indices 和 col_indices 索引 2D 数组 x,您只需使用以下语法:

<code class="python">x_indexed = x[row_indices, col_indices]</code>
登录后复制

但是,如果 row_indices 和 col_indices 的形状不兼容广播,则可能会遇到广播错误。为了克服这个问题,您可以使用 np.ix 来处理广播。

<code class="python">x_indexed = x[np.ix_(row_indices, col_indices)]</code>
登录后复制

使用布尔掩码

您还可以使用布尔掩码进行行和列选择。创建两个布尔掩码,row_mask 和 col_mask,其中 True 表示要选择的元素。

然后,您可以使用以下语法:

<code class="python">x_indexed = x[row_mask, col_mask]</code>
登录后复制

示例:

给定x、row_indices 和 col_indices:

<code class="python">x = np.random.randint(0, 10, size=(5, 8))
row_indices = [2, 1, 4]
col_indices = [3, 7]

# Using broadcasting with indexing arrays
x_indexed_broadcasting = x[np.ix_(row_indices, col_indices)]

# Using boolean masks
row_mask = np.array([False] * 5, dtype=bool)
row_mask[[2, 1, 4]] = True
col_mask = np.array([False] * 8, dtype=bool)
col_mask[[3, 7]] = True
x_indexed_masks = x[row_mask, col_mask]

print(x_indexed_broadcasting)
print(x_indexed_masks)</code>
登录后复制

输出:

两种方法产生相同的结果:

[[4 7]
 [7 7]
 [2 1]]
登录后复制

以上是如何使用两个索引列表对 2D NumPy 数组进行索引,以及广播问题的解决方案是什么?的详细内容。更多信息请关注PHP中文网其他相关文章!

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