Home > Backend Development > Python Tutorial > How to Efficiently Find Row Indexes of Multiple Values in NumPy Arrays?

How to Efficiently Find Row Indexes of Multiple Values in NumPy Arrays?

Linda Hamilton
Release: 2024-12-03 07:24:13
Original
814 people have browsed it

How to Efficiently Find Row Indexes of Multiple Values in NumPy Arrays?

Finding Row Indexes of Multiple Values in NumPy Arrays

Given an array X and a set of target rows searched_values, the task is to retrieve the corresponding row indexes. This problem can be solved efficiently using various NumPy functions.

Approach 1: Broadcasting

A simple approach using broadcasting:

np.where((X==searched_values[:,None]).all(-1))[1]
Copy after login

Approach 2: Memory-Efficient Conversion

For memory efficiency, convert each row to a unique linear index and use np.in1d:

dims = X.max(0)+1
out = np.where(np.in1d(np.ravel_multi_index(X.T,dims),\
                    np.ravel_multi_index(searched_values.T,dims)))[0]
Copy after login

Approach 3: Memory-Efficient Search

Another memory-efficient solution using np.searchsorted:

dims = X.max(0)+1
X1D = np.ravel_multi_index(X.T,dims)
searched_valuesID = np.ravel_multi_index(searched_values.T,dims)
sidx = X1D.argsort()
out = sidx[np.searchsorted(X1D,searched_valuesID,sorter=sidx)]
Copy after login

Note: This approach assumes that each row in searched_values has a match in X.

The above is the detailed content of How to Efficiently Find Row Indexes of Multiple Values in NumPy 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template