Find indices of a list of values in a not sorted numpy array
<p>I'm referring to a similar question: <a href="http://stackoverflow.com/questions/12122639">Find indices of a list of values in a numpy array</a></p>

<p>In that case we have a master array that is sorted and another array of which we want to find the index in the master array.</p>

<pre><code>master = np.array([1,2,3,4,5])
search = np.array([4,2,2,3])
</code></pre>

<p>The suggested solution was:</p>

<pre><code>&gt;&gt;&gt; master = np.array([1,2,3,4,5])
&gt;&gt;&gt; search = np.array([4,2,2,3])
&gt;&gt;&gt;np.searchsorted(master, search)
array([3, 1, 1, 2])
</code></pre>

<p>But what if master is not sorted?
for example if i have two arrays like this where the first one is not sorted:</p>

<pre><code>&gt;&gt;&gt;master = np.array([2,3,5,4,1])
&gt;&gt;&gt;search = np.array([3,2,1,4,5])
</code></pre>

<p>i get:</p>

<pre><code>&gt;&gt;&gt; np.searchsorted(master, search)
array([1, 0, 0, 2, 5])
</code></pre>

<p>But instead i would like:</p>

<pre><code>array([1,0,4,3,2])
</code></pre>

<p>i.e. the indices of items in search in master.</p>

<p>How do i get them possibly with a native function of numpy?(not using [np.where(master==i) for i in search] )</p>

<p>Thanks</p>

<p>EDIT: 
In this case the search array  is a permutation of master. Then i would like to find how the index of master are permuted to give a permuted array like search.</p>

<p>As general case, search array contain some item that maybe contained or not in the master such as:</p>

<pre><code>&gt;&gt;&gt;master = np.array([2,3,5,4,1])
&gt;&gt;&gt;search = np.array([1,4,7])
</code></pre>

<p>If all else fails, you need to sort your master array temporarily, then invert the sort order needed for this after matching the elements:</p>

<pre><code>import numpy as np

master = np.array([2,3,5,4,1])
search = np.array([3,2,1,4,5])

# sorting permutation and its reverse
sorti = np.argsort(master)
sorti_inv = np.empty(sorti.shape,dtype=np.int64)
sorti_inv[sorti] = np.arange(sorti.size)

# get indices in sorted version
tmpind = np.searchsorted(master,search,sorter=sorti)

# transform indices back to original array with inverse permutation
final_inds = tmpind[sorti_inv]
</code></pre>

<p>The result of the above is correctly</p>

<pre><code>array([1, 0, 4, 3, 2])
</code></pre>

<hr>

<p>As you noted in a comment, your specific <code>search</code> and <code>master</code> are permutations of each other. In this case you can alternatively sort <em>both</em> arrays, and use the inverse permutation combined with the other direct permutation:</p>

<pre><code>sorti = np.argsort(master)
sorti_inv = np.empty(sorti.shape,dtype=np.int64)
sorti_inv[sorti] = np.arange(sorti.size)
sorti_s = np.argsort(search)
final_inds = sorti_s[sorti_inv]
</code></pre>

<p>One should consider the effort needed to search two arrays vs searching one array in the sorted version of another. I really can't tell which one's faster.</p>

python arrays numpy