Find cells in dataframe where value is between x and y
<p>I want all values in a pandas dataframe as True / False depending on whether the value is between the given x and y.</p>

<p>Any combining of 2 dataframes using an 'AND' operator, or any 'between' functionality from pandas would be nice. I would prefer not to loop over the columns and call the pandas.Series.between(x, y) function.</p>

<p><strong>Example</strong></p>

<p>Given the following dataframe</p>

<pre><code>&gt;&gt;&gt; df = pd.DataFrame([{1:1,2:2,3:6},{1:9,2:9,3:10}])
&gt;&gt;&gt; df
   1  2   3
0  1  2   6
1  9  9  10
</code></pre>

<p>I want all values between x and y. I can for example start with:</p>

<pre><code>&gt;&gt;&gt; df &gt; 2
       1      2     3
0  False  False  True
1   True   True  True
</code></pre>

<p>and then do </p>

<pre><code>&gt;&gt;&gt; df &lt; 10
      1     2      3
0  True  True   True
1  True  True  False
</code></pre>

<p>But then</p>

<pre><code>&gt;&gt;&gt; df &gt; 2 and df &lt; 10
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
  File "C:\Users\Laurens Koppenol\Anaconda2\lib\site-packages\pandas\core\generic.py", line 731, in __nonzero__
    .format(self.__class__.__name__))
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
</code></pre>

<p><code>between</code> is a convenient method for this.  However, it is only for series objects.  we can get around this by either using <code>apply</code> which operates on each row (or column) which is a series.  Or, reshape the dataframe to a series with <code>stack</code></p>

<p>use <code>stack</code>, <code>between</code>, <code>unstack</code></p>

<pre><code>df.stack().between(2, 10, inclusive=False).unstack()
</code></pre>

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

python pandas