Pandas series filtering between values

If s

is pandas.Series

, I know I can do this:

b = s < 4

      

or

b = s > 0

      

but i can't do

b = 0 < s < 4

      

or

b = (0 < s) and (s < 4)

      

What is pandas idiomatic method to create logical series based on logical AND / OR / NOT of other boolean series?

+3


source to share


2 answers


found it ... the operator works &

, but you need to use parentheses to take precedence on the right and avoid the error:



>>> import pandas as pd
>>> s1 = pd.Series([0,1,2,3,4,5,6,0,1,2,3,4])
>>> (s1 < 4) & (s1 > 0)
0     False
1      True
2      True
3      True
4     False
5     False
6     False
7     False
8      True
9      True
10     True
11    False
dtype: bool
>>> s1 < 4 & s1 > 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "c:\app\python\anaconda\1.6.0\lib\site-packages\pandas\core\generic.py",
line 698, in __nonzero__
    .format(self.__class__.__name__))
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

      

+3


source


You can also use .between

:

s1.between(0, 4, inclusive=False)

      



A bit verbose, but since it shouldn't create 2 intermediate rows it should be faster (admittedly untested).

+2


source







All Articles