在
or和
andpython语句需要
truth-值。因为
pandas这些被认为是模棱两可的,所以你应该使用
"bitwise" |(or)or&(and)操作:
result = result[(result['var']>0.25) | (result['var']<-0.25)]
对于此类数据结构,它们会重载以产生元素级
or(或
and)。
只是为该语句添加更多解释:
当你想获取的时
bool,会引发异常
pandas.Series:
>>> import pandas as pd>>> x = pd.Series([1])>>> bool(x)ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
什么你打是一处经营隐含转换的操作数
bool(你用
or,但它也恰好为
and,
if和
while):
>>> x or xValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().>>> x and xValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().>>> if x:... print('fun')ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().>>> while x:... print('fun')ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().除了这些4个语句有一些隐藏某几个Python函数bool调用(如
any,all,filter,...),这些都是通常不会有问题的
pandas.Series,但出于完整性我想提一提这些。
在你的情况下,该异常并没有真正的帮助,因为它没有提到正确的替代方法。对于
and和,
or你可以使用(如果需要逐元素比较):
numpy.logical_or:
>>> import numpy as np>>> np.logical_or(x, y)
或简单地
|算:
>>> x | y
numpy.logical_and:
>>> np.logical_and(x, y)
或简单地
&算:
>>> x & y
如果你使用的是运算符,请确保由于运算符优先级而正确设置了括号。
有几个逻辑numpy的功能,它应该工作的pandas.Series。
如果你在执行if或时遇到异常,则异常中提到的替代方法更适合while。我将在下面简短地解释每个:
如果要检查你的系列是否为空:
>>> x = pd.Series([])>>> x.emptyTrue>>> x = pd.Series([1])>>> x.emptyFalse
如果没有明确的布尔值解释,
Python通常会将
len容器的
gth(如
list,,tuple...)解释为真值。因此,如果你想进行类似
python的检查,可以执行:
if x.size或
if not x.empty代替
if x。
如果你仅Series包含一个布尔值:
>>> x = pd.Series([100])>>> (x > 50).bool()True>>> (x < 50).bool()False
如果要检查系列的第一个也是唯一的一项(例如,.bool()但即使不是布尔型内容也可以使用):
>>> x = pd.Series([100])>>> x.item()100
如果要检查所有或任何项目是否为非零,非空或非假:
>>> x = pd.Series([0, 1, 2])>>> x.all() # because one element is zeroFalse>>> x.any() # because one (or more) elements are non-zeroTrue



