0

I have two identically-sized numpy ndarrays with permuted rows:

import numpy as np
a = np.ndarray([[1,2,3],
                [4,5,6],
                [7,8,9],
                [10,11,12]])
b = np.ndarray([[7,8,9],
                [10,11,12],
                [1,2,3],
                [4,5,6]])

I want a function that returns the indices of each row in first array, relative to the second array. For example:

compare_row_indices(a,b)

would return

[2,3,0,1] # 0-based indexing

What is the most pythonic way to implement this function?

Pete
  • 504
  • 4
  • 15

1 Answers1

1

Maybe not the best possible way, but this seems to work (breaking it down to multiple steps for easier visualization):

>>> cmp = a[:, None] == b
>>> cmp
array([[[False, False, False],
        [False, False, False],
        [ True,  True,  True],
        [False, False, False]],

       [[False, False, False],
        [False, False, False],
        [False, False, False],
        [ True,  True,  True]],

       [[ True,  True,  True],
        [False, False, False],
        [False, False, False],
        [False, False, False]],

       [[False, False, False],
        [ True,  True,  True],
        [False, False, False],
        [False, False, False]]])
>>> eq = np.all(cmp, axis=-1)
>>> eq
array([[False, False,  True, False],
       [False, False, False,  True],
       [ True, False, False, False],
       [False,  True, False, False]])
>>> np.argwhere(eq)
array([[0, 2],
       [1, 3],
       [2, 0],
       [3, 1]])
>>> np.argwhere(eq)[:, 1]
array([2, 3, 0, 1])
Alok Singhal
  • 93,253
  • 21
  • 125
  • 158
  • Perfect, thanks! In one line, this yields: `yo = np.argwhere(np.all(a[:, None] == b, axis=-1))[:, 1]` – Pete Feb 03 '19 at 21:11