Given an array X and a set of target rows searched_values, the task is to retrieve the corresponding row indexes. This problem can be solved efficiently using various NumPy functions.
A simple approach using broadcasting:
np.where((X==searched_values[:,None]).all(-1))[1]
For memory efficiency, convert each row to a unique linear index and use 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]
Another memory-efficient solution using 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)]
Note: This approach assumes that each row in searched_values has a match in X.
The above is the detailed content of How to Efficiently Find Row Indexes of Multiple Values in NumPy Arrays?. For more information, please follow other related articles on the PHP Chinese website!