首页  >  文章  >  后端开发  >  如何使用两个索引列表来索引 2D NumPy 数组?

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

Linda Hamilton
Linda Hamilton原创
2024-10-27 02:40:30705浏览

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

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