`np.ix_` 如何簡化多維 NumPy 陣列中的索引選擇和分配?

Mary-Kate Olsen
發布: 2024-10-26 19:38:02
原創
1011 人瀏覽過

How can `np.ix_` simplify index selection and assignment in multidimensional NumPy arrays?

使用 np.ix_ 索引數組和布林遮罩以進行索引選擇或分配

可以使用 np.ix_ 簡化在多維 NumPy 數組中操作選擇或分配。其工作原理如下:

1.使用索引數組

A. Selection

np.ix_ 允許您將索引數組分組為更高維度的組合以索引多維數組。若要使用兩個一維索引數組(例如row_indices 和col_indices)進行選擇,請使用:

<code class="python">x_indexed = x[np.ix_(row_indices, col_indices)]</code>
登入後複製

這相當於巢狀版本,其中外部索引數組(例如row_indices)針對內部索引數組進行廣播索引數組(col_indices):

<code class="python">x_indexed = x[np.asarray(row_indices)[:,None], col_indices]</code>
登入後複製

B.賦值

同樣,使用np.ix_建立的索引數組元組,可以直接完成標量賦值或資料區塊的廣播:

<code class="python">x[np.ix_(row_indices, col_indices)] = scalar # assign a scalar
x[np.ix_(row_indices, col_indices)] = block  # assign a broadcastable block</code>
登入後複製

2.使用布林遮罩

np.ix_ 也適用於布林遮罩:

A.選擇

要使用布林遮罩(row_mask 和col_mask)選擇資料區塊,請使用:

<code class="python">x[np.ix_(row_mask, col_mask)]</code>
登入後複製

B.作業

對於帶有布林遮罩的作業,請使用:

<code class="python">x[np.ix_(row_mask, col_mask)] = scalar # assign a scalar
x[np.ix_(row_mask, col_mask)] = block  # assign a broadcastable block</code>
登入後複製

以上是`np.ix_` 如何簡化多維 NumPy 陣列中的索引選擇和分配?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!