首頁  >  文章  >  後端開發  >  如何使用兩個索引清單對 2D NumPy 陣列進行索引,以及廣播問題的解決方案是什麼?

如何使用兩個索引清單對 2D NumPy 陣列進行索引,以及廣播問題的解決方案是什麼?

Patricia Arquette
Patricia Arquette原創
2024-10-26 15:06:02746瀏覽

How can I index a 2D NumPy array using two lists of indices, and what are the solutions to broadcasting issues?

使用2 個索引清單對2D Numpy 陣列進行索引

在NumPy 中,有多種方法使用兩個索引來索引2D 數組索引列表,一個用於行,一個用於列。讓我們探索這些方法並解決廣播問題。

透過索引陣列使用廣播

要使用兩個索引陣列row_indices 和col_indices 索引2D 陣列x,您只需使用以下語法:

<code class="python">x_indexed = x[row_indices, col_indices]</code>

但是,如果row_indices 和col_indices 的形狀不相容廣播,則可能會遇到廣播錯誤。為了克服這個問題,您可以使用 np.ix 來處理廣播。

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

使用布林遮罩

您也可以使用布林遮罩進行行和列選擇。建立兩個布林掩碼,row_mask 和 col_mask,其中 True 表示要選擇的元素。

然後,您可以使用以下語法:

<code class="python">x_indexed = x[row_mask, col_mask]</code>

範例:

給定x、row_indices 和col_indices:

<code class="python">x = np.random.randint(0, 10, size=(5, 8))
row_indices = [2, 1, 4]
col_indices = [3, 7]

# Using broadcasting with indexing arrays
x_indexed_broadcasting = x[np.ix_(row_indices, col_indices)]

# Using boolean masks
row_mask = np.array([False] * 5, dtype=bool)
row_mask[[2, 1, 4]] = True
col_mask = np.array([False] * 8, dtype=bool)
col_mask[[3, 7]] = True
x_indexed_masks = x[row_mask, col_mask]

print(x_indexed_broadcasting)
print(x_indexed_masks)</code>

輸出:

兩種方法產生相同的結果:

[[4 7]
 [7 7]
 [2 1]]

以上是如何使用兩個索引清單對 2D NumPy 陣列進行索引,以及廣播問題的解決方案是什麼?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn