Invalid syntax error in for loop pandas
<p>I am new to pandas and While trying to iterate over the rows through a for loop I am getting a Invalid syntax error in pandas </p>

<p>Below is the code I tried </p>

<pre><code>for index, row in df.iterrows(): 
if ((df['c1'] == 'cond1')&amp;(df['c2']=='cond2')):
df['c3']='cond2'
elif ((df['c1'] == 'cond3')&amp;(df['c2']=='cond2')):
df['c3']='cond2'
elif ((df['c1'] == 'cond4')&amp;(df['c2']=='cond2')):
df['c3']='cond2'
else:
df['c3']='Nan'
df
</code></pre>

<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.ix.html" rel="nofollow"><code>ix</code></a>, but are you sure you need always string <code>cond2</code> get to column <code>c3</code>?</p>

<pre><code>df['c3']='Nan'
df.ix[(df['c1'] == 'cond1')&amp;(df['c2']=='cond2'), 'df3'] = 'cond2'
df.ix[(df['c1'] == 'cond3')&amp;(df['c2']=='cond2'), 'df3'] = 'cond2'
df.ix[(df['c1'] == 'cond4')&amp;(df['c2']=='cond2'), 'df3'] = 'cond2'
</code></pre>

<p>Sample:</p>

<pre><code>import pandas as pd
import numpy as np

df = pd.DataFrame({'c1':['cond1','cond2','cond3','cond4'],
                   'c2':['cond2','cond2','cond2','cond2']})

print (df)
      c1     c2
0  cond1  cond2
1  cond2  cond2
2  cond3  cond2
3  cond4  cond2

#set to NaN value
df['c3']= np.nan
#set to string 'Nan'
#df['c3']= 'Nan'

df.ix[(df['c1'] == 'cond1')&amp;(df['c2']=='cond2'), 'c3'] = 'a'
df.ix[(df['c1'] == 'cond3')&amp;(df['c2']=='cond2'), 'c3'] = 'b'
df.ix[(df['c1'] == 'cond4')&amp;(df['c2']=='cond2'), 'c3'] = 'c'
print (df)
      c1     c2   c3
0  cond1  cond2    a
1  cond2  cond2  NaN
2  cond3  cond2    b
3  cond4  cond2    c
</code></pre>

<hr>

<p>Looping solution is very slow, but if need it, you need use <code>row</code> instead <code>df</code> in loop:</p>

<pre><code>import pandas as pd
import numpy as np

df = pd.DataFrame({'c1':['cond1','cond2','cond3','cond4'],
                   'c2':['cond2','cond2','cond2','cond2']})

print (df)

df['c3'] = ''
for index, row in df.iterrows(): 
    if ((row['c1'] == 'cond1')&amp;(row['c2']=='cond2')):
        row['c3']='a'
    elif ((row['c1'] == 'cond3')&amp;(row['c2']=='cond2')):
        row['c3']='b'
    elif ((row['c1'] == 'cond4')&amp;(row['c2']=='cond2')):
        row['c3']='c'
    else:
        row['c3']=np.nan

print (df)
      c1     c2   c3
0  cond1  cond2    a
1  cond2  cond2  NaN
2  cond3  cond2    b
3  cond4  cond2    c
</code></pre>

python pandas for-loop