Home >Backend Development >Python Tutorial >How to Efficiently Find Row Indices Matching Values in a NumPy Array?
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.
np.where((X==searched_values[:,None]).all(-1))[1]
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]
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.
When selecting dimensions for np.ravel_multi_index to generate unique linear indices, consider the following:
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!