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

Linda Hamilton
Release: 2024-10-27 02:40:30
Original
724 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!