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!