python - Get rows of a first array matching rows of a second one -
suppose have array a
of shape (m, k)
, b
of shape (n, k)
.
the rows of b
possible patterns can encountered (each pattern 1d array of size k
).
i array c
of shape (m,)
c[i]
indice of pattern (in b
) of row i
in a
.
i doing in loop (i.e. looping on possible patterns) end using vectorization.
here example:
a = np.array([[0, 1], [0, 1], [1, 0]]) b = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
i expecting:
c = np.array([1, 1, 2])
based on this solution
, here's vectorized solution using np.searchsorted
-
dims = b.max(0)+1 a1d = np.ravel_multi_index(a.t,dims) b1d = np.ravel_multi_index(b.t,dims) sidx = b1d.argsort() out = sidx[np.searchsorted(b1d,a1d,sorter=sidx)]
sample run -
in [43]: out[43]: array([[72, 89, 75], [72, 89, 75], [93, 38, 61], [47, 67, 50], [47, 67, 50], [93, 38, 61], [72, 89, 75]]) in [44]: b out[44]: array([[47, 67, 50], [93, 38, 61], [41, 55, 27], [72, 89, 75]]) in [45]: out out[45]: array([3, 3, 1, 0, 0, 1, 3])
Comments
Post a Comment