Create dataframe column with elif of different types in pandas
<p>This is an extension of <a href="http://stackoverflow.com/questions/18194404/create-column-with-elif-in-pandas">question</a>.</p>

<p>I'd like to do some if/elif/else logic to create a dataframe column, pseudocode example:</p>

<pre><code>if Col1 = 'A' and Col2 = 1 then Col3 = 'A1'
else if Col1 = 'A' and Col2 = 0 then Col3 = 'A0'
else Col3 = 'XX'
</code></pre>

<p>is it ok to mix up the types there? I'm getting this error:</p>

<blockquote>
  <p>TypeError: cannot compare a dtyped [int64] array with a scalar of type [bool]</p>
</blockquote>

<p>I think you can use:</p>

<pre><code>df['Col3'] = 'XX'
df.loc[(df.Col1 == 'A') &amp; (df.Col2 == 1), 'Col3'] = 'A1'
df.loc[(df.Col1 == 'A') &amp; (df.Col2 == 0), 'Col3'] = 'A0'
</code></pre>

<p>With double <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html" rel="nofollow"><code>numpy.where</code></a>:</p>

<pre><code>df["Col3"] = np.where((df.Col1 == 'A') &amp; (df.Col2 == 1) , "A1", 
             np.where((df.Col1 == 'A') &amp; (df.Col2 == 0), 'A0', 'XX'))
</code></pre>

<p>Sample:</p>

<pre><code>df = pd.DataFrame({'Col1':['A','B','A','B'],
                   'Col2':[1,1,0,0]})

print (df)
  Col1  Col2
0    A     1
1    B     1
2    A     0
3    B     0

df['Col3'] = 'XX'
df.loc[(df.Col1 == 'A') &amp; (df.Col2 == 1), 'Col3'] = 'A1'
df.loc[(df.Col1 == 'A') &amp; (df.Col2 == 0), 'Col3'] = 'A0'

df["Col4"] = np.where((df.Col1 == 'A') &amp; (df.Col2 == 1) , "A1", 
             np.where((df.Col1 == 'A') &amp; (df.Col2 == 0), 'A0', 'XX'))

print (df)
  Col1  Col2 Col3 Col4
0    A     1   A1   A1
1    B     1   XX   XX
2    A     0   A0   A0
3    B     0   XX   XX
</code></pre>

python pandas indexing condition multiple-columns