pandas 值之间的熊猫系列过滤

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27929583/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 22:50:40  来源:igfitidea点击:

pandas series filtering between values

pythonpandas

提问by Jason S

If sis a pandas.Series, I know I can do this:

如果s是 a pandas.Series,我知道我可以这样做:

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 the idiomatic pandas method for creating a boolean series based on the logical AND / OR / NOT of other boolean series?

基于其他布尔系列的逻辑 AND / OR / NOT 创建布尔系列的惯用Pandas方法是什么?

采纳答案by Jason S

found it... the &operator works, but you need to use parentheses to get the precedence right and avoid an 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.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().

回答by fantabolous

You can also use .between:

您还可以使用.between

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

A bit verbose but as it doesn't have to create 2 intermediary series it should be faster (admittedly untested).

有点冗长,但因为它不必创建 2 个中间系列,所以它应该更快(诚然未经测试)。