ホームページ  >  記事  >  バックエンド開発  >  2 つのインデックスのリストを使用して 2D NumPy 配列にインデックスを付ける方法

2 つのインデックスのリストを使用して 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_ を使用する

2 つのリストを使用して 2D NumPy 配列にインデックスを作成するにはインデックス、配列の np.ix_ 関数を配列のインデックス付けと組み合わせて使用​​できます。

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

マスク付きの np.ix_ の使用

あるいは、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>

以上が2 つのインデックスのリストを使用して 2D NumPy 配列にインデックスを付ける方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。