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