我想用 or
条件过滤我的数据框,以保留特定列的值在 [-0.25, 0.25]
范围之外的行。我试过了:
df = df[(df['col'] < -0.25) or (df['col'] > 0.25)]
但我得到了错误:
Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()
最佳答案
or
和 and
python 语句需要 truth
值。对于 pandas
,这些被认为是模棱两可的,因此您应该使用“按位”|
(或)或 &
(和)操作:
df = df[(df['col'] < -0.25) | (df['col'] > 0.25)]
这些类型的数据结构被重载以产生元素方式的or
或and
。
只是为这个声明添加更多解释:
当你想获取 pandas.Series
的 bool
时抛出异常:
>>> 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 x
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
>>> x and x
ValueError: 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
没有问题,但为了完整起见,我想提及这些。
在您的情况下,该异常(exception)并没有真正的帮助,因为它没有提及正确的替代方案。对于 and
和 or
,如果您想要逐元素比较,可以使用:
-
>>> import numpy as np >>> np.logical_or(x, y)
或者只是
|
操作符:>>> x | y
-
>>> np.logical_and(x, y)
或者只是
&
操作符:>>> x & y
如果您使用运算符,请务必正确设置括号,因为 operator precedence .
有several logical numpy functions 应该在 pandas.Series
上工作。
如果您在执行 if
或 while
时遇到异常中提到的替代方案,则更适合。我将简要解释其中的每一个:
如果您想检查您的系列是否为空:
>>> x = pd.Series([]) >>> x.empty True >>> x = pd.Series([1]) >>> x.empty False
如果没有明确的 boolean 解释。因此,如果你想要类似 python 的检查,你可以这样做:
if x.size
或if not x.empty
而不是if x
。如果您的
Series
包含 一个且只有一个 boolean 值:>>> x = pd.Series([100]) >>> (x > 50).bool() True >>> (x < 50).bool() False
如果您想检查您的系列的第一个也是唯一一个项目(如
.bool()
,但即使对于非 boolean 内容也有效):>>> x = pd.Series([100]) >>> x.item() 100
如果您想检查 all 或 any 项是否非零、非空或非假:
>>> x = pd.Series([0, 1, 2]) >>> x.all() # because one element is zero False >>> x.any() # because one (or more) elements are non-zero True
关于python - Series 的真值是不明确的。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36921951/