Home > Backend Development > Python Tutorial > How to Efficiently Select Specific Columns per Row in NumPy Using Lists or Boolean Arrays?

How to Efficiently Select Specific Columns per Row in NumPy Using Lists or Boolean Arrays?

DDD
Release: 2024-11-01 10:52:30
Original
429 people have browsed it

How to Efficiently Select Specific Columns per Row in NumPy Using Lists or Boolean Arrays?

Efficiently Selecting Specific Columns per Row in NumPy Using Lists or Boolean Arrays

NumPy offers extensive capabilities for manipulating multidimensional arrays. However, selecting specific columns based on a list of indexes for each row can be challenging and demand efficient solutions.

One approach to solving this issue is to utilize boolean arrays. Each column of a boolean array can represent the desired selection for a particular row. By using direct selection with the boolean array, specific columns can be extracted efficiently. For instance:

<code class="python">import numpy as np

a = np.array([1, 2, 3])
b = np.array([[False, True, False], [True, False, False], [False, False, True]])
a[b]
# Output: [2, 4, 9]</code>
Copy after login

Alternatively, it's possible to create an array representing the range of columns and use direct selection on it. This approach, however, may not always be optimal.

<code class="python">a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
a[np.arange(len(a)), [1, 0, 2]]
# Output: [2, 4, 9]</code>
Copy after login

By leveraging these methods, it's feasible to efficiently select specific columns per row in NumPy arrays, regardless of whether the selection criteria are provided as a list of indexes or a boolean array.

The above is the detailed content of How to Efficiently Select Specific Columns per Row in NumPy Using Lists or Boolean Arrays?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template