首頁  >  文章  >  後端開發  >  如何使用兩個索引列表來索引 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