社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Peter Mortensen MSeifert  »  全部回复
回复总数  2
5 年前
回复了 Peter Mortensen MSeifert 创建的主题 » 在python中,与(and,&,or,|)等价的是什么?

熊猫中布尔索引的逻辑运算符

重要的是要认识到,您不能使用任何Python 逻辑运算符 ( and , or 或 not )在 pandas.Series 或 pandas.DataFrame s(同样,您不能在 numpy.array (包含多个元素)。之所以不能使用这些函数,是因为它们隐式地调用 bool 在其操作数上引发异常,因为这些数据结构决定数组的布尔值不明确:

>>> import numpy as np
>>> import pandas as pd
>>> arr = np.array([1,2,3])
>>> s = pd.Series([1,2,3])
>>> df = pd.DataFrame([1,2,3])
>>> bool(arr)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> bool(s)
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
>>> bool(df)
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

我做了更广泛的报道 in my answer to the "Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()" Q+A .

NumPy的逻辑函数

然而 NumPy 为这些运算符提供元素级操作等价物,作为可在上使用的函数 努比。大堆 , 熊猫。系列 , 熊猫。数据帧 ,或任何其他(合规) 努比。大堆 子类:

df1 和 df2 以下是数据帧):

np.logical_and(df1, df2)
np.logical_or(df1, df2)
np.logical_not(df1)
np.logical_xor(df1, df2)

布尔函数的位函数和位运算符

但是,如果您有布尔NumPy数组、熊猫系列或熊猫数据帧,您也可以使用 element-wise bitwise functions (对于布尔函数来说,它们与逻辑函数是——或者至少应该是——无法区分的):

通常使用运算符。然而,当与比较运算符结合使用时,必须记住将比较括在括号中,因为按位运算符具有 higher precedence than the comparison operators :

(df1 < 10) | (df2 > 10)  # instead of the wrong df1 < 10 | df2 > 10

这可能会令人恼火,因为Python逻辑运算符的优先级低于比较运算符,所以您通常会编写 a < 10 and b > 10 (在哪里 a 和 b 例如,是简单整数),不需要括号。

逻辑运算和按位运算之间的差异(在非布尔运算上)

必须强调的是,位运算和逻辑运算仅对布尔NumPy数组(以及布尔级数和数据帧)等效。如果这些不包含布尔值,那么这些操作将给出不同的结果。我将包括使用NumPy数组的示例,但熊猫数据结构的结果将类似:

>>> import numpy as np
>>> a1 = np.array([0, 0, 1, 1])
>>> a2 = np.array([0, 1, 0, 1])

>>> np.logical_and(a1, a2)
array([False, False, False,  True])
>>> np.bitwise_and(a1, a2)
array([0, 0, 0, 1], dtype=int32)

由于NumPy(和类似的熊猫)对布尔值做了不同的事情( Boolean or “mask” index arrays )和整数( Index arrays )索引索引的结果也会有所不同:

>>> a3 = np.array([1, 2, 3, 4])

>>> a3[np.logical_and(a1, a2)]
array([4])
>>> a3[np.bitwise_and(a1, a2)]
array([1, 1, 1, 2])

汇总表

Logical operator | NumPy logical function | NumPy bitwise function | Bitwise operator
-------------------------------------------------------------------------------------
       and       |  np.logical_and        | np.bitwise_and         |        &
-------------------------------------------------------------------------------------
       or        |  np.logical_or         | np.bitwise_or          |        |
-------------------------------------------------------------------------------------
                 |  np.logical_xor        | np.bitwise_xor         |        ^
-------------------------------------------------------------------------------------
       not       |  np.logical_not        | np.invert              |        ~

哪里 逻辑运算符不适用于NumPy阵列 、熊猫系列和熊猫数据帧。其他人处理这些数据结构(以及普通Python对象)和工作元素。 但是,在普通Python上使用位反转时要小心 布尔 s,因为在这种情况下bool将被解释为整数(例如 ~False 返回 -1 和 ~True 返回 -2 ).

5 年前
回复了 Peter Mortensen MSeifert 创建的主题 » 在python中,与(and,&,or,|)等价的是什么?

当你说

(a['x']==1) and (a['y']==10)

您隐式地要求Python进行转换 (a['x']==1) 和 (a['y']==10) 设置为布尔值。

NumPy数组(长度大于1)和Pandas对象(如Series)没有布尔值——换句话说,它们提高了

ValueError:数组的真值不明确。使用a.empty、a.any()或a.all()。

当用作布尔值时。那是因为 unclear when it should be True or False .一些用户可能会认为,如果它们的长度不是零,比如Python列表,那么它们是真的。其他人可能希望它是真实的,但前提是 全部的 它的元素是真实的。其他人可能希望这是真的,如果 任何 它的许多元素都是真实的。

因为有太多相互矛盾的期望,NumPy和Pandas的设计师拒绝猜测,反而提出了一个错误。

相反,您必须通过调用 empty() , all() 或 any() 方法来指示您想要的行为。

然而,在本例中,看起来您不想要布尔求值,而是想要 元素方面 逻辑与。这就是 & 二进制运算符执行以下操作:

(a['x']==1) & (a['y']==10)

返回一个布尔数组。


顺便说一下 alexpmil notes , 括号是强制性的,因为 & 有更高的 operator precedence 比 == .

没有括号, a['x']==1 & a['y']==10 将被评估为 a['x'] == (1 & a['y']) == 10 这就相当于链式比较 (a['x'] == (1 & a['y'])) and ((1 & a['y']) == 10) .这是形式的表达 Series and Series . 使用 and 用两个系列会再次触发相同的 ValueError 如上所述。这就是为什么括号是强制性的。