How to iterate over pandas dataframe and create new column
<p>I have a pandas dataframe that has 2 columns. I want to loop through it's rows and based on a string from column 2 I would like to add a string in a newly created 3th column. I tried:</p>

<pre><code>for i in df.index:
    if df.ix[i]['Column2']==variable1:
        df['Column3'] = variable2
    elif df.ix[i]['Column2']==variable3:
        df['Column3'] = variable4

print(df)
</code></pre>

<p>But the resulting dataframe has in column 3 only Variable2.</p>

<p>Any ideas how else I could do this?</p>

<p>I think you can use double <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html" rel="nofollow"><code>numpy.where</code></a>, what is faster as loop:</p>

<pre><code>df['Column3'] = np.where(df['Column2']==variable1, variable2, 
                np.where(df['Column2']==variable3, variable4))
</code></pre>

<p>And if need add variable if both conditions are <code>False</code>:</p>

<pre><code>df['Column3'] = np.where(df['Column2']==variable1, variable2, 
                np.where(df['Column2']==variable3, variable4, variable5))
</code></pre>

<p>Sample:</p>

<pre><code>df = pd.DataFrame({'Column2':[1,2,4,3]})
print (df)
   Column2
0        1
1        2
2        4
3        3

variable1 = 1
variable2 = 2
variable3 = 3
variable4 = 4
variable5 = 5

df['Column3'] = np.where(df['Column2']==variable1, variable2, 
                np.where(df['Column2']==variable3, variable4, variable5))

print (df)
   Column2  Column3
0        1        2
1        2        5
2        4        5
3        3        4
</code></pre>

<p>Another solution, thanks <a href="http://stackoverflow.com/questions/39873995/how-to-iterrate-over-pandas-dataframe-and-create-new-column/39874053#comment67034759_39874053"><code>Jon Clements</code></a>:</p>

<pre><code>df['Column4'] = df.Column2.map({variable1: variable2, variable3:variable4}).fillna(variable5)
print (df)
   Column2  Column3  Column4
0        1        2      2.0
1        2        5      5.0
2        4        5      5.0
3        3        4      4.0
</code></pre>

python loops pandas condition multiple-columns