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

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

Barbara Streisand
Barbara StreisandOriginal
2024-12-07 06:16:13208browse

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

Find the Row Indexes of Several Values in a Numpy Array

Problem:

We are given a NumPy array X and a set of values searched_values. The objective is to determine the row indices in X that correspond to each of the values in searched_values.

For instance, for the following input arrays:

X = np.array([[4,  2],
              [9,  3],
              [8,  5],
              [3,  3],
              [5,  6]])

searched_values = np.array([[4, 2],
                            [3, 3],
                            [5, 6]])

The desired output should be:

[0, 3, 4]

Approach #1: NumPy Broadcasting

This approach utilizes NumPy broadcasting to perform element-wise comparisons between X and each row of searched_values:

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

Approach #2: Memory Efficient Conversion using np.in1d

To conserve memory, we can convert each row of X and searched_values into linear index equivalents and then apply np.in1d for intersection:

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]

Approach #3: Memory Efficient Conversion using np.searchsorted

Another memory-efficient approach using np.searchsorted and the same philosophy of linear index conversion:

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)]

Understanding np.ravel_multi_index

np.ravel_multi_index converts each row of X into a unique linear index equivalent. It operates on a 2D array of n-dimensional indices and the shape of the n-dimensional grid that these indices are to be mapped onto.

For instance, in our example, each row of X represents an indexing tuple for a 2D grid with dimensions dims. np.ravel_multi_index maps each of these tuples to a unique linear index.

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