What do &=, |=, and ~ do in Pandas
<p>I frequently see code like this at work:</p>

<pre><code>overlap &amp;= group['ADMSN_DT'].loc[i] &lt;= group['epi_end'].loc[j]
</code></pre>

<p>My question is what do operators such as <code>&amp;=</code>, <code>|=</code>, and <code>~</code> do in pandas?</p>

<p>From the <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow">documentation</a></p>

<blockquote>
  <p>The operators are: | for or, &amp; for and, and ~ for not. These must be
  grouped by using parentheses.</p>
</blockquote>

<p><a href="https://docs.python.org/3/reference/simple_stmts.html#augmented-assignment-statements" rel="nofollow">Augmented assignment statements</a></p>

<blockquote>
  <p>An augmented assignment evaluates the target (which, unlike normal
  assignment statements, cannot be an unpacking) and the expression
  list, performs the binary operation specific to the type of assignment
  on the two operands, and assigns the result to the original target.
  The target is only evaluated once.</p>
</blockquote>

<p>just like <code>a += 1</code> increments <code>a</code>, <code>a &amp;= b</code> compares <code>a</code> and <code>b</code> and assigns the result to <code>a</code>.</p>

<pre><code>a = 1
b = 0
print(a &amp; b)
&gt;&gt;&gt; 0
a &amp;= b
print(a)
&gt;&gt;&gt; 0
</code></pre>

<p>And a <code>pandas</code> example</p>

<p>Let's generate a dataframe of zeros and ones.</p>

<pre><code>import numpy as np
import pandas as pd
a = pd.DataFrame(np.random.randint(0, 2, size=(6,4)), columns=list('ABCD'))
b = pd.DataFrame(np.random.randint(0, 2, size=(6,4)), columns=list('ABCD'))
</code></pre>

<p>Our initial dataframe</p>

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

<blockquote>
<pre><code>   A  B  C  D
0  0  1  1  0
1  0  0  1  0
2  1  0  0  1
3  1  1  0  0
4  0  0  0  1
5  0  0  0  0
</code></pre>
</blockquote>

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

<blockquote>
<pre><code>   A  B  C  D
0  0  0  0  0
1  1  1  1  0
2  0  1  1  1
3  0  1  1  1
4  1  1  1  0
5  1  1  1  1
</code></pre>
</blockquote>

<p>The 4th row of <code>a</code> and <code>b</code></p>

<pre><code>print(a.loc[3])
</code></pre>

<blockquote>
<pre><code>A    1
B    1
C    0
D    0
Name: 1, dtype: int32
</code></pre>
</blockquote>

<pre><code>print(b.loc[3])
</code></pre>

<blockquote>
<pre><code>A    0
B    1
C    1
D    1
Name: 1, dtype: int32
</code></pre>
</blockquote>

<p>Now evaluate and assign row 4</p>

<pre><code>a.loc[3] &amp;= b.loc[3]
</code></pre>

<p>Row 4 of <code>a</code> has changed. Only where both rows have 1 at the same position a 1 is written back to <code>a</code>.</p>

<pre><code>print(a.loc[3])
</code></pre>

<blockquote>
<pre><code>A    0
B    1
C    0
D    0
Name: 3, dtype: int32
</code></pre>
</blockquote>

python python-2.7 pandas