find and replace using multiple criteria pandas python
<p>I have the following dataframe (df):</p>

<pre><code>loc pop_1   source_1    pop_2   source_2
a   99  group_a 77  group_b
b   93  group_a 90  group_b
c   58  group_a 59  group_b
d   47  group_a 62  group_b
</code></pre>

<p>I create an additional column 'upper_limit':</p>

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

<p>I now want to add another column that looks at the values in 'upper_limit', compares them to pop_1 and pop_2 and then selects the text from source_1 or source_2 when they match. I.e:</p>

<pre><code>loc pop_1   source_1    pop_2   source_2 upper_limit source
a   99  group_a 77  group_b 99 group_a
b   93  group_a 90  group_b 93 group_a
c   58  group_a 59  group_b 59 group_b
d   47  group_a 62  group_b 62 group_b
</code></pre>

<p>I have tried to create a dict from pop_1 and source_1 through:</p>

<pre><code>table_dict = df[['pop_1','source_1']]
z = table_dict.to_dict
</code></pre>

<p>And then map this using:</p>

<pre><code>df['source'] = 'n/a'
df['source'].replace(z,inplace=True)
</code></pre>

<p>This returns the dataframe but with the column 'source' only showing n/a results. </p>

<blockquote>
  <p>I now want to add another column that looks at the values in 'upper_limit', compares them to pop_1 and pop_2 and then selects the text from source_1 or source_2 when they match.</p>
</blockquote>

<p>You can do it much more simply using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow"><code>np.where</code></a>:</p>

<pre><code>In [19]: import numpy as np

In [20]: df['upper_limit source'] = np.where(df.upper_limit == df.pop_1, df.source_1, df.source_2)

In [20]: df
Out[20]: 
  loc  pop_1  pop_2 source_1 source_2  upper_limit upper_limit source
0   a     99     77  group_a  group_b           99            group_a
1   b     93     90  group_a  group_b           93            group_a
2   c     58     59  group_a  group_b           59            group_b
3   d     47     62  group_a  group_b           62            group_b
</code></pre>

python pandas