Series 的真值是不明确的。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()

新手上路,请多包涵

我想使用 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 许可协议

阅读 2.3k
2 个回答

orand python 语句需要 truth 。对于 pandas ,这些被认为是不明确的,因此您应该使用“按位” | (或)或 & (和)操作:

 df = df[(df['col'] < -0.25) | (df['col'] > 0.25)]

对于这些类型的数据结构,它们被重载以产生元素方式 orand


只是为了对此声明添加更多解释:

当您想要获取 boolpandas.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().

What you hit was a place where the operator implicitly converted the operands to bool (you used or but it also happens for and , ifwhile ):

 >>> 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().

Besides these 4 statements there are several python functions that hide some bool calls (like any , all , filter , …)这些通常与 pandas.Series 没有问题,但为了完整起见,我想提及这些。


在您的情况下,异常并没有真正的帮助,因为它没有提到 正确的替代品。对于 andor ,如果你想要逐元素比较,你可以使用:

     >>> import numpy as np
    >>> np.logical_or(x, y)

或者只是 | 运算符:

     >>> x | y

     >>> np.logical_and(x, y)

或者只是 & 运算符:

     >>> x & y

如果您使用运算符,请确保正确设置括号,因为 运算符优先级

几个逻辑 numpy 函数 应该 适用于 pandas.Series


如果您在执行 ifwhile 时遇到异常中提到的替代方案,则更适合。我将简要解释其中的每一个:

  • 如果您想检查您的系列是否为
     >>> x = pd.Series([])
    >>> x.empty
    True
    >>> x = pd.Series([1])
    >>> x.empty
    False

Python 通常将 len 的容器(如 list , tuple , …)解释为真值,如果它没有明确的 boole 解释。因此,如果您想要类似 python 的检查,您可以这样做: if x.sizeif 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 zero
    False
    >>> x.any()   # because one (or more) elements are non-zero
    True

原文由 MSeifert 发布,翻译遵循 CC BY-SA 4.0 许可协议

熊猫按位使用 & | 并且每个条件都应该包装在 ()

例如以下作品

data_query = data[(data['year'] >= 2005) & (data['year'] <= 2010)]

但是没有适当括号的相同查询不会

data_query = data[(data['year'] >= 2005 & data['year'] <= 2010)]

原文由 Nipun 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题