In pandas dataframe, generate third column data based on results in two other columns
<p>I'm a newbie to dataframes.  I have columns <code>A</code>, <code>B</code> and <code>C</code> and want to use the data in A and B to create a value in C.  For example, if <code>A = 1</code> and/or <code>B = 1</code>, then I want to place a <code>1</code> in column <code>C</code> and do this logic for all rows in the dataframe.</p>

<p>e.g. starting array:</p>

<pre><code>         A  B  C
0        1  0  
1        0  1  
2        1  1  
3        0  0  
</code></pre>

<p>etc  </p>

<p>resulting array:</p>

<pre><code>         A  B  C
0        1  0  1
1        0  1  1
2        1  1  1
3        0  0  0
</code></pre>

<p>etc</p>

<p>Use <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['C'] = np.where(df.A | df.B, 1, 0)
print (df)
   A  B  C
0  0  0  0
1  0  1  1
2  1  0  1
3  1  1  1

df['C'] = np.where((df.A == 0) &amp; (df.B == 0), 0, 1)
print (df)
   A  B  C
0  0  0  0
1  0  1  1
2  1  0  1
3  1  1  1
</code></pre>

<p>Or simplier convert boolean <code>Series</code> to <code>int</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.astype.html" rel="nofollow"><code>astype</code></a>:</p>

<pre><code>df['C'] = (df.A | df.B).astype(int)
print (df)
   A  B  C
0  0  0  0
1  0  1  1
2  1  0  1
3  1  1  1

df['C'] = (~((df.A == 0) &amp; (df.B == 0))).astype(int)
print (df)
   A  B  C
0  0  0  0
1  0  1  1
2  1  0  1
3  1  1  1
</code></pre>

python pandas dataframe boolean condition