wowzer
wowzer

Reputation: 25

How to find indices of elements in one array by matching the same elements in another array?

I have two arrays, A and B. The elements in A are in B but in a different order column-wise only. How do I essentially match the elements in A to the exact ones in B column-wise and find their indices in B?

To be clear, the 9 in the first column of A should check its index in the first column of B and return it (i.e., (4, 0)).

And then the 6 in the first column of A should check its index in the first column of B and return it (i.e., (1, 0)).

And then the 5 in the first column of A should check its index in the first column of B and return it (i.e., (0, 0)).

Repeat until the 3 in the first column of A checks its index in the first column of B and return it (i.e., (2, 0)).

Moving on to the second column of A, the 6 should check its index in the second column of B and return it (i.e., (4, 1)).

Then the 3 in the second column of A should check its index in the second column of B and return it (i.e., (1,1)).

Repeat until you hit the 0 (last element) in the second column of A and find its index in the second column of B and return in (i.e., (2, 1)).

Repeat the steps until the last column of A.

I hope this makes sense. Appreciate any help!

A = [[9, 6, 7, 12, 13, 10, 11], [6, 3, 4, 9, 10, 7, 8], [5, 2, 3, 8, 9, 6, 7], [4, 1, 2, 7, 8, 5, 6], [3, 0, 1, 6, 7, 4, 5]]
B = [[5, 2, 3, 8, 9, 6, 7], [6, 3, 4, 9, 10, 7, 8], [3, 0, 1, 6, 7, 4, 5], [4, 1, 2, 7, 8, 5, 6], [9, 6, 7, 12, 13, 10, 11]]

Upvotes: 0

Views: 366

Answers (1)

T C Molenaar
T C Molenaar

Reputation: 3260

You can do the following using numpy:

A = [[9,  6,  7, 12, 13, 10, 11], [6,  3,  4,  9, 10,  7,  8], [5,  2,  3,  8,  9,  6,  7], [4,  1,  2,  7,  8,  5,  6], [3,  0,  1,  6,  7,  4,  5]] 
B = [[5,  2,  3,  8,  9,  6,  7], [6,  3,  4,  9, 10,  7,  8], [3,  0,  1,  6,  7,  4,  5], [4,  1,  2,  7,  8,  5,  6], [9,  6,  7, 12, 13, 10, 11]]

A = np.array(A)
B = np.array(B)

shp = A.shape

C = np.zeros(shp)

for col in range(shp[1]):
    B_col = B[:, col]
    for row in range(shp[0]):
        value = A[row, col]
        B_row = np.where(B_col == value)[0][0]
        C[row, col] = int(str(B_row) + str(col))
        # print((row, col), 'in A with value:', A[row, col], 'matches:', (B_row, col))

output:

array([[40., 41., 42., 43., 44., 45., 46.],
       [10., 11., 12., 13., 14., 15., 16.],
       [ 0.,  1.,  2.,  3.,  4.,  5.,  6.],
       [30., 31., 32., 33., 34., 35., 36.],
       [20., 21., 22., 23., 24., 25., 26.]])

Or if you want the transpose, you can do C.T or do C[col, row] instead of C[row, col] in the for-loop.

Upvotes: 1

Related Questions