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>Firstly, there is no need to loop through each and every index, just use pandas built in <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#the-where-method-and-masking" rel="nofollow">boolean indexing</a>. First line here, we gather all of the values in <code>Column2</code> that are the same as <code>variable1</code> and set the same row in <code>Column3</code> to be <code>variable2</code></p>

<pre><code>df.ix[df.Column2==variable1, 'Column3'] = variable2
df.ix[df.Column2==variable3, 'Column3'] = variable4
</code></pre>

<p>A simple example would be</p>

<pre><code>import pandas as pd

df = pd.DataFrame({'Animal':['dog', 'fish', 'fish', 'dog']})
print(df)

    Animal
0   dog
1   fish
2   fish
3   dog

df.ix[df.Animal=='dog', 'Colour'] = 'brown'
df.ix[df.Animal=='fish', 'Colour'] = 'silver'
print(df)

    Animal  Colour
0   dog     brown
1   fish    silver
2   fish    silver
3   dog     brown
</code></pre>

<p>The above method can be build on very easily using multiple conditions like <code>&amp;</code> and <code>|</code> to boolean index.</p>

<pre><code>df = pd.DataFrame({'Animal':['dog', 'fish', 'fish', 'dog'], 'Age': [1, 3, 2, 10]})
print(df)

   Age Animal
0    1    dog
1    3   fish
2    2   fish
3   10    dog

df.ix[(df.Animal=='dog') &amp; (df.Age &gt; 8), 'Colour'] = 'grey' # old dogs go grey
df.ix[(df.Animal=='dog') &amp; (df.Age &lt;= 8), 'Colour'] = 'brown'
df.ix[df.Animal=='fish', 'Colour'] = 'silver'
print(df)

   Age Animal  Colour
0    1    dog   brown
1    3   fish  silver
2    2   fish  silver
3   10    dog    grey
</code></pre>

python loops pandas condition multiple-columns