我想使用 or
条件过滤我的数据框,以保留特定列的值超出范围 [-0.25, 0.25]
的行。我试过了:
df = df[(df['col'] < -0.25) or (df['col'] > 0.25)]
但我得到了错误:
Series 的真值是不明确的。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()
原文由 obabs 发布,翻译遵循 CC BY-SA 4.0 许可协议
我想使用 or
条件过滤我的数据框,以保留特定列的值超出范围 [-0.25, 0.25]
的行。我试过了:
df = df[(df['col'] < -0.25) or (df['col'] > 0.25)]
但我得到了错误:
Series 的真值是不明确的。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()
原文由 obabs 发布,翻译遵循 CC BY-SA 4.0 许可协议
4 回答4.5k 阅读✓ 已解决
1 回答3.3k 阅读✓ 已解决
4 回答3.8k 阅读✓ 已解决
3 回答2.2k 阅读✓ 已解决
1 回答4.5k 阅读✓ 已解决
1 回答3.9k 阅读✓ 已解决
1 回答2.8k 阅读✓ 已解决
or
和and
python 语句需要truth
。对于pandas
,这些被认为是不明确的,因此您应该使用“按位”|
(或)或&
(和)操作:对于这些类型的数据结构,它们被重载以产生元素方式
or
或and
。只是为了对此声明添加更多解释:
当您想要获取
bool
的pandas.Series
时,将引发异常:What you hit was a place where the operator implicitly converted the operands to
bool
(you usedor
but it also happens forand
,if
和while
):Besides these 4 statements there are several python functions that hide some
bool
calls (likeany
,all
,filter
, …)这些通常与pandas.Series
没有问题,但为了完整起见,我想提及这些。在您的情况下,异常并没有真正的帮助,因为它没有提到 正确的替代品。对于
and
和or
,如果你想要逐元素比较,你可以使用:numpy.logical_or
:或者只是
|
运算符:numpy.logical_and
:或者只是
&
运算符:如果您使用运算符,请确保正确设置括号,因为 运算符优先级。
有 几个逻辑 numpy 函数 应该 适用于
pandas.Series
。如果您在执行
if
或while
时遇到异常中提到的替代方案,则更适合。我将简要解释其中的每一个:Python 通常将
len
的容器(如list
,tuple
, …)解释为真值,如果它没有明确的 boole 解释。因此,如果您想要类似 python 的检查,您可以这样做:if x.size
或if not x.empty
而不是if x
。Series
包含 一个且只有一个 布尔值:.bool()
但即使对于非布尔内容也适用):