Finding index by iterating over each row of matrix
<p>I have an numpy array 'A' of size <code>5000x10</code>. I also have another number <code>'Num'</code>. I want to apply the following to each row of A:</p>

<pre><code>import numpy as np
np.max(np.where(Num &gt; A[0,:]))
</code></pre>

<p>Is there a pythonic way than writing a for loop for above.</p>

<p>You could use <code>argmax</code> -</p>

<pre><code>A.shape[1] - 1 - (Num &gt; A)[:,::-1].argmax(1)
</code></pre>

<p>Alternatively with <code>cumsum</code> and <code>argmax</code> -</p>

<pre><code>(Num &gt; A).cumsum(1).argmax(1)
</code></pre>

<p><strong>Explanation :</strong> With <code>np.max(np.where(..)</code>, we are basically looking to get the last occurrence of matches along each row on the comparison.</p>

<p>For the same, we can use <code>argmax</code>. But, <code>argmax</code> on a boolean array gives us the first occurrence and not the last one. So, one trick is to perform the comparison and flip the columns with <code>[:,::-1]</code> and then use <code>argmax</code>. The column indices are then subtracted by the number of cols in the array to make it trace back to the original order.</p>

<p>On the second approach, it's very similar to a <a href="http://stackoverflow.com/a/39959511/3293881"><code>related post</code></a> and therefore quoting from it :</p>

<p>One of the uses of argmax is to get ID of the first occurence of the max element along an axis in an array . So, we get the cumsum along the rows and get the first max ID, which represents the last non-zero elem. This is because cumsum on the leftover elements won't increase the sum value after that last non-zero element.</p>

python numpy vectorization