Isolating pandas columns using boolean logic in python
<p>I am trying to grab the rows of a data frame that satisfy one or both of the following boolean statements:</p>

<pre><code>1) df['colName'] == 0
2) df['colName'] == 1
</code></pre>

<p>I've tried these, but neither one works (throws errors):</p>

<pre><code>df = df[df['colName']==0 or df['colName']==1]
df = df[df['colName']==0 | df['colName']==1]
</code></pre>

<p>Any other ideas?</p>

<p>You could clean up what you've done using <code>eq</code> instead of <code>==</code></p>

<pre><code>df[df.colName.eq(0) | df.colName.eq(1)]
</code></pre>

<p>For this case, I recommend using <code>isin</code></p>

<pre><code>df[df.colName.isin([0, 1])]
</code></pre>

<p>Using <code>query</code> also works but is slower</p>

<pre><code>df.query('colName in [0, 1]')
</code></pre>

<hr>

<p><strong><em>Timing</em></strong><br>
<code>isin</code> is quickest on <code>df</code> defined below<br>
<code>df = pd.DataFrame(np.random.randint(3, size=10000), columns=['colName'])</code></p>

<p><a href="http://i.stack.imgur.com/tS95z.png" rel="nofollow"><img src="http://i.stack.imgur.com/tS95z.png" alt="enter image description here"></a></p>

python pandas dataframe