Performing complex conditional operation on numpy arrays
<pre><code>import numpy as np

mat_a = np.random.random((5, 5))
mat_b = np.random.random((5, 5))
mat_c = np.random.random((5, 5))
</code></pre>

<p>Lets say for a specific grid cell, the values in the same position in the 3 arrays are as follows:<br>
<code>mat_a, A = 0.3</code><br>
<code>mat_b, B = 0.2</code><br>
<code>mat_c, C = 0.1</code>  </p>

<p>Here, we find the array with the least value, in this case it is C  </p>

<ol>
<li><p>We compute the amount of <code>C</code> that should be allocated to <code>B</code> as <code>0.1 * (0.2/ (0.2 + 0.3))</code> i.e. Value of cell in <code>C</code> multiplied by  the fraction of <code>B</code> with <code>total</code> being <code>A + B</code>. The newly computed value is stored in a <code>2D</code> array called <code>C_B</code>  </p></li>
<li><p>Similarly, the amount of <code>C</code> that should be allocated to <code>A</code> is <code>0.1 * (0.3/(0.2 + 0.3))</code>. The newly computed value is stored in a <code>2D</code> array called <code>C_A</code>.</p></li>
<li><p>We repeat this process for cells where least value is in array <code>B</code>, storing the newly computed results in <code>2D</code> arrays <code>B_C</code> and <code>B_A</code> respectively.</p></li>
<li><p>We repeat this process for cells where least value is in array <code>A</code>, storing the newly computed results in <code>2D</code> arrays <code>A_C</code> and <code>A_B</code> respectively.</p></li>
</ol>

<p>The only way I can think of doing this is using nested for loops, but that would be prohibitive for larger arrays and not very pythonic. Is there a fast and pythonic solution?</p>

<p>-- edit</p>

<p><code>C_B</code> should contain 0 where <code>mat_c</code> does not contain smallest value </p>

<p>One solution is to calculate all values, replace unwanted ones with zeros.</p>

<pre><code>mat_a = np.random.random((5, 5))
mat_b = np.random.random((5, 5))
mat_c = np.random.random((5, 5))
bigmat = np.stack((mat_a, mat_b, mat_c)) # this is a 3, 5, 5 array
minima = np.argmin(bigmat, axis=0) # contains a 5x5 array of 0,1,2 for a,b,c respectively
c_a = mat_c * mat_a / (mat_b + mat_c)
c_a[minima != 2] = 0
</code></pre>

<p>You can repeat this for the other 5 answer arrays. Or, you could also do:</p>

<pre><code>c_a = np.zeros((5,5))
c_a[minima == 2] = (mat_c * mat_a / (mat_b + mat_c))[minima == 2]
</code></pre>

python numpy