如何使用两个索引列表来索引 2D NumPy 数组?

Linda Hamilton
发布: 2024-10-27 02:40:30
原创
724 人浏览过

How to Index a 2D NumPy Array Using Two Lists of Indices?

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

将 np.ix_ 与索引数组结合使用

使用两个列表对 2D NumPy 数组进行索引索引、数组,我们可以将 np.ix_ 函数与索引数组结合使用。

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

将 np.ix_ 与 Masks 结合使用

或者,我们可以将 np.ix_ 与用于选择和索引数组的布尔掩码:

<code class="python">row_mask = [0, 1, 1, 0, 0, 1, 0]
col_mask = [1, 0, 1, 0, 1, 1, 0, 0]

x_indexed = x[np.ix_(row_mask, col_mask)]</code>
登录后复制

示例

考虑以下示例:

<code class="python">import numpy as np

x = np.random.randint(0, 6, (20, 8))

row_indices = [4, 2, 18, 16, 7, 19, 4]
col_indices = [1, 2]</code>
登录后复制

要使用提供的列表索引 x,我们可以使用任一方法:

<code class="python"># Using np.ix_ with indexing arrays
x_indexed = x[np.ix_(row_indices, col_indices)]

# Using np.ix_ with masks
row_mask = np.isin(np.arange(x.shape[0]), row_indices)
col_mask = np.isin(np.arange(x.shape[1]), col_indices)

x_indexed = x[np.ix_(row_mask, col_mask)]</code>
登录后复制

两种方法都会产生所需的索引数组:

<code class="python">>>> x_indexed
array([[76, 56],
       [70, 47],
       [46, 95],
       [76, 56],
       [92, 46]])</code>
登录后复制

以上是如何使用两个索引列表来索引 2D NumPy 数组?的详细内容。更多信息请关注PHP中文网其他相关文章!

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