To index a 2D NumPy array using two lists of indices, arrays,, we can use the np.ix_ function in conjunction with indexing arrays.
<code class="python">x_indexed = x[np.ix_(row_indices, col_indices)]</code>
Alternatively, we can use np.ix_ with boolean masks to select and index the array:
<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>
Consider the following example:
<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>
To index x using the provided lists, we can use either method:
<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>
Both methods will result in the desired indexed array:
<code class="python">>>> x_indexed array([[76, 56], [70, 47], [46, 95], [76, 56], [92, 46]])</code>
The above is the detailed content of How to Index a 2D NumPy Array Using Two Lists of Indices?. For more information, please follow other related articles on the PHP Chinese website!