python - Row indices of unique numpy array (not element) from a larger numpy array - TagMerge
2Row indices of unique numpy array (not element) from a larger numpy arrayRow indices of unique numpy array (not element) from a larger numpy array

Row indices of unique numpy array (not element) from a larger numpy array

Asked 1 years ago
0
2 answers

You can transform your 2D array into a 1D view (see this answer), then use numpy.isin:

def view1D(a, b):
    a = np.ascontiguousarray(a)
    b = np.ascontiguousarray(b)
    void_dt = np.dtype((np.void, a.dtype.itemsize * a.shape[1]))
    return a.view(void_dt).ravel(),  b.view(void_dt).ravel()

A,B = view1D(a.T, b[:2].T)

b.T[np.isin(B, A)][:,2]
# array([11, 13, 15, 18])

Source: link

0

Another option, if you do not want to flatten your arrays, is to make them the same size and compare them element-wise:

a, b = a.T, b.T
tile_a = np.tile(a, b[: , :2].shape[0]).reshape(a.shape[0] * b[: , :2].shape[0], a.shape[1])
indices = np.argwhere((tile_a == np.concatenate([b[:, :2]]*a.shape[0])).all(axis=1))
indices[indices > 0] -= 1 

print(np.squeeze(b[indices // a.shape[0]], axis=1)[:, 2])
#[11 13 15 18]

Source: link

Recent Questions on python

    Programming Languages