Home > Backend Development > Python Tutorial > How to Efficiently Find Row Indices of Multiple Values in a NumPy Array?

How to Efficiently Find Row Indices of Multiple Values in a NumPy Array?

Barbara Streisand
Release: 2024-12-12 18:44:11
Original
458 people have browsed it

How to Efficiently Find Row Indices of Multiple Values in a NumPy Array?

How to Find the Row Indexes of Several Values in a NumPy Array?

NumPy offers several approaches to locate the row indexes of specified values within a NumPy array:

Approach #1: NumPy Broadcasting

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

Approach #2: Memory-Efficient Approach with np.ravel_multi_index

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 Approach with 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

Understanding np.ravel_multi_index

np.ravel_multi_index converts multi-dimensional indexing tuples into linear indices for a grid. It assumes each column represents a dimension and uses the grid shape to compute linear indices.

For example, with X:

X = np.array([[4, 2],
              [9, 3]])
Copy after login

and dims = [10, 7], the first row of X (4, 2) is converted to the linear index 30. This corresponds to row 4 and column 2 on the grid:

dims = X.max(0) + 1 # [10, 7]
np.ravel_multi_index(X.T, dims) # [30, 66]
Copy after login

Choosing Dimensions for Unique Linear Indices

To ensure unique linear indices, the grid's dimensions should be set to the maximum stretch of each axis of the input array X. This can be achieved by adding 1 to the maximum value of each column in X.

The above is the detailed content of How to Efficiently Find Row Indices of Multiple Values in a NumPy Array?. 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