multiple conditions for np.where python pandas
<p>I have the following dataframe:</p>

<pre><code>region  pop_1   pop_1_source    pop_2   pop_2_source    pop_3   pop_3_source
a   99  x1  84  x2  61  x3
b   64  x1  65  x2  16  x3
c   92  x1  26  x2  6   x3  
d   82  x1  60  x2  38  x3
e   45  x1  77  x2  42  x3
</code></pre>

<p>I can calculate the highest value found in each region through:</p>

<pre><code>df['upper_limit'] = df[['pop_1','pop_2','pop_3']].max(axis=1)
</code></pre>

<p>If I only compare two populations I can then calculate the source of the highest population i.e:</p>

<pre><code>df['upper_limit_source'] = np.where(df.upper_limit == df['upper_limit'],df.pop_1,df.pop_2)
</code></pre>

<p>However if I try expand this to search into all three columns, it fails to work.
I have searched for a solution, but cannot make anything work with np.where(np.logical_or or similar. </p>

<p>Am I missing something obvious? </p>

<p>I found your question a bit confusing (among other things, <code>df.upper_limit == df['upper_limit']</code> is always true, and your "source" columns are all filled with <code>x1</code> (except for one <code>1x</code> which looks like a typo)). </p>

<p>However, it seems like you'd like to find <em>which</em> of the three columns was responsible for the maximum, then calculate a value based on this. So, to calculate the column responsible, you could use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html" rel="nofollow"><code>np.argmax</code></a>:</p>

<pre><code>import numpy as np

idmax = np.argmax(df[['pop_1','pop_2','pop_3']].as_matrix(), axis=1)
</code></pre>

<p>This will give you, for each row, 0, 1, or 2, depending on which of the three columns was responsible for the maximum.</p>

<p>Now if, for example, you'd like to choose <code>pop_1_source</code>, <code>pop_2_source</code>, or <code>pop_3_source</code>, according to the index, you could use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.choose.html" rel="nofollow"><code>np.choose</code></a>:</p>

<pre><code>np.choose(idmax, df[[`pop_1_source', 'pop_2_source', pop_3_source']].as_matrix().T)
</code></pre>

python pandas