Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In numpy, how to create an array of the indices of the elements in a source array as they are found in a destination array?

Tags:

python

numpy

I'm sure this question has been answered somewhere, but I just can't find the words to look for it.

I have these two arrays:

import numpy as np

src = np.array([[8, 1],
                [2, 4]]) 

dst = np.array([[1, 4],
                [8, 2]]) 

I would like to get this array:

indices = (np.array([[1, 0],
                     [1, 0]]),
           np.array([[0, 0],
                     [1, 1]]))

Such that dst[indices] gets me src.

Any ideas? Moreover, what is the kind of operation that I'm looking for called? So that I can search more about it by myself in the future.

like image 565
LoneCodeRanger Avatar asked Mar 02 '23 00:03

LoneCodeRanger


1 Answers

Here is what I believe is the "direct" way:

# find order of src and dst
so = src.ravel().argsort()
do = dst.ravel().argsort()
# allocate combined map
tot = np.empty_like(src)

# next line is all you need to remember
tot.ravel()[so] = do

# go back to 2D indexing
indices = np.unravel_index(tot,dst.shape)

# check
dst[indices]
# array([[8, 1],
#        [2, 4]])

indices
# (array([[1, 0],
#         [1, 0]]), array([[0, 0],
#         [1, 1]]))
like image 186
Paul Panzer Avatar answered Mar 04 '23 12:03

Paul Panzer