如何使用兩個索引列表來索引 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學習者快速成長!