在or和andpython语句需要truth-值。因为pandas这些被认为是模棱两可的,所以您应该使用“按位” |(或)或&(和)操作:
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解决方法
在用or条件过滤我的结果数据帧时遇到问题。我希望我的结果df提取var大于0.25且小于-0.25的所有列值。
下面的逻辑为我提供了一个模糊的真实值,但是当我将此过滤分为两个单独的操作时,它可以工作。这是怎么回事 不知道在哪里使用建议a.empty(),a.bool(),a.item(),a.any() or a.all()。
result = result[(result[’var’]>0.25) or (result[’var’]<-0.25)]