Home  >  Article  >  Backend Development  >  How to Index a 2D NumPy Array Using Two Lists of Indices?

How to Index a 2D NumPy Array Using Two Lists of Indices?

Linda Hamilton
Linda HamiltonOriginal
2024-10-27 02:40:30705browse

How to Index a 2D NumPy Array Using Two Lists of Indices?

Indexing a 2D NumPy Array with 2 Lists of Indices

Using np.ix_ with Indexing Arrays

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>

Using np.ix_ with Masks

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>

Example

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn