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

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

Barbara Streisand
Barbara StreisandOriginal
2024-12-15 18:06:12657browse

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

Find the Row Indexes of Various Values in a Numpy Array

1. Understanding the Problem

Given an array X and an array searched_values, the task is to find the indices of rows in X that match the corresponding rows in searched_values.

2. Approach Using NumPy Broadcasting

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

3. Memory-Efficient Approach Using np.ravel_multi_index and 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]

4. Understanding np.ravel_multi_index

np.ravel_multi_index converts a 2D array of n-dimensional indices to linear index equivalents. For example, given X and dims, it would compute:

np.ravel_multi_index(X.T,dims)

Resulting in [30, 66, 61, 24, 41], where each number represents the linear index equivalent of the corresponding row in X.

5. Choosing Dimensions for Unique Linear Indices

When selecting dimensions for np.ravel_multi_index to generate unique linear indices, consider the following:

  • Each column in the input array (X) represents one axis of the grid being mapped to.
  • To ensure unique linear indices, the maximum stretch of each axis should be considered, which is the maximum value in each column plus 1.

For the given X:

dims = X.max(0)+1 # [10, 7]

This would create a grid with at least the specified dimensions, ensuring unique linear indices.

The above is the detailed content of How to Efficiently Find Row Indices Matching 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