社区所有版块导航
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学习  »  Python

在python中,与(and,&,or,|)等价的是什么?

edshewa • 4 年前 • 1942 次点击  

我正在处理熊猫中的布尔索引。

问题是为什么会有这样的声明:

a[(a['some_column']==some_number) & (a['some_other_column']==some_other_number)]

很好,但是

a[(a['some_column']==some_number) and (a['some_other_column']==some_other_number)]

错误退出?

例子:

a = pd.DataFrame({'x':[1,1],'y':[10,20]})

In: a[(a['x']==1)&(a['y']==10)]
Out:    x   y
     0  1  10

In: a[(a['x']==1) and (a['y']==10)]
Out: ValueError: The truth value of an array with more than one element is ambiguous.     Use a.any() or a.all()
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/133281
文章 [ 3 ]  |  最新文章 4 年前
Peter Mortensen MSeifert
Reply   •   1 楼
Peter Mortensen MSeifert    5 年前

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

重要的是要认识到,您不能使用任何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 ).

Peter Mortensen MSeifert
Reply   •   2 楼
Peter Mortensen MSeifert    5 年前

当你说

(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 如上所述。这就是为什么括号是强制性的。

cs95
Reply   •   3 楼
cs95    7 年前

太长,读不下去了 熊猫中的逻辑运算符是 & , | 和 ~ ,和括号 (...) 这很重要!

蟒蛇的 and , or 和 not 逻辑运算符设计用于处理标量。所以Pandas必须做得更好,重写位运算符以实现 矢量化 此功能的(元素)版本。

下面是python中的( exp1 和 exp2 是计算为布尔结果的表达式)。。。

exp1 and exp2              # Logical AND
exp1 or exp2               # Logical OR
not exp1                   # Logical NOT

...将转化为。。。

exp1 & exp2                # Element-wise logical AND
exp1 | exp2                # Element-wise logical OR
~exp1                      # Element-wise logical NOT

为了熊猫。

如果在执行逻辑运算的过程中 ValueError ,则需要使用括号进行分组:

(exp1) op (exp2)

例如

(df['col1'] == x) & (df['col2'] == y) 

等等


Boolean Indexing :常见的操作是通过逻辑条件计算布尔掩码以过滤数据。熊猫提供 三 操作员: & 对于逻辑和逻辑, | 用于逻辑OR,以及 ~ 当然不是。

考虑以下设置:

np.random.seed(0)
df = pd.DataFrame(np.random.choice(10, (5, 3)), columns=list('ABC'))
df

   A  B  C
0  5  0  3
1  3  7  9
2  3  5  2
3  4  7  6
4  8  8  1

逻辑与

对于 df 上面,假设您希望返回A<5和B>5.这是通过分别计算每个条件的掩码,并对它们进行求和来实现的。

按位重载 & 操作人员
在继续之前,请注意这些文件的特别摘录,其中

另一种常见的操作是使用布尔向量来过滤 数据运营商包括: | 对于 或 , & 对于 和 和 ~ 对于 不 . 这些 ,因为默认情况下Python将 计算表达式,例如 df.A > 2 & df.B < 3 像 df.A > (2 & df.B) < 3 ,而所需的评估顺序为 (df.A > 2) & (df.B < 3) .

因此,考虑到这一点,元素逻辑AND可以通过位运算符实现 & :

df['A'] < 5

0    False
1     True
2     True
3     True
4    False
Name: A, dtype: bool

df['B'] > 5

0    False
1     True
2    False
3     True
4     True
Name: B, dtype: bool

(df['A'] < 5) & (df['B'] > 5)

0    False
1     True
2    False
3     True
4    False
dtype: bool

接下来的过滤步骤很简单,

df[(df['A'] < 5) & (df['B'] > 5)]

   A  B  C
1  3  7  9
3  4  7  6

括号用于覆盖按位运算符的默认优先顺序,按位运算符的优先级高于条件运算符 < 和 > .参见 Operator Precedence 在python文档中。

如果不使用括号,则表达式的计算结果不正确。例如,如果您不小心尝试了以下操作:

df['A'] < 5 & df['B'] > 5

它被解析为

df['A'] < (5 & df['B']) > 5

这就变成了,

df['A'] < something_you_dont_want > 5

这就变成了(参见上的python文档) chained operator comparison ),

(df['A'] < something_you_dont_want) and (something_you_dont_want > 5)

这就变成了,

# Both operands are Series...
something_else_you_dont_want1 and something_else_you_dont_want2

哪个扔

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

所以,不要犯那个错误! 1.

避免括号分组
解决方法其实很简单。对于数据帧,大多数操作符都有相应的绑定方法。如果单个掩码是使用函数而不是条件运算符构建的,则不再需要按参数分组来指定求值顺序:

df['A'].lt(5)

0     True
1     True
2     True
3     True
4    False
Name: A, dtype: bool

df['B'].gt(5)

0    False
1     True
2    False
3     True
4     True
Name: B, dtype: bool

df['A'].lt(5) & df['B'].gt(5)

0    False
1     True
2    False
3     True
4    False
dtype: bool

请参阅 Flexible Comparisons. .总结一下,我们有

╒════╤════════════╤════════════╕
│    │ Operator   │ Function   │
╞════╪════════════╪════════════╡
│  0 │ >          │ gt         │
├────┼────────────┼────────────┤
│  1 │ >=         │ ge         │
├────┼────────────┼────────────┤
│  2 │ <          │ lt         │
├────┼────────────┼────────────┤
│  3 │ <=         │ le         │
├────┼────────────┼────────────┤
│  4 │ ==         │ eq         │
├────┼────────────┼────────────┤
│  5 │ !=         │ ne         │
╘════╧════════════╧════════════╛

避免使用括号的另一个选项是使用 DataFrame.query (或 eval ):

df.query('A < 5 and B > 5')

   A  B  C
1  3  7  9
3  4  7  6

我有 广泛地 记录在案 query 和 评估 在里面 Dynamic Expression Evaluation in pandas using pd.eval() .

operator.and_
允许您以功能性方式执行此操作。内部通话 Series.__and__ 它对应于按位运算符。

import operator 

operator.and_(df['A'] < 5, df['B'] > 5)
# Same as,
# (df['A'] < 5).__and__(df['B'] > 5) 

0    False
1     True
2    False
3     True
4    False
dtype: bool

df[operator.and_(df['A'] < 5, df['B'] > 5)]

   A  B  C
1  3  7  9
3  4  7  6

你通常不需要这个,但知道它很有用。

概括起来: np.logical_and (及 logical_and.reduce )
另一种选择是使用 NP逻辑_和 ,也不需要括号:

np.logical_and(df['A'] < 5, df['B'] > 5)

0    False
1     True
2    False
3     True
4    False
Name: A, dtype: bool

df[np.logical_and(df['A'] < 5, df['B'] > 5)]

   A  B  C
1  3  7  9
3  4  7  6

NP逻辑_和 是一个 ufunc (Universal Functions) ,而且大多数UFUNC都有 reduce 方法这意味着更容易概括 logical_and 如果你有多个口罩和。比如说,戴口罩和口罩 m1 和 m2 和 m3 具有 & ,你必须这么做

m1 & m2 & m3

然而,一个更简单的选择是

np.logical_and.reduce([m1, m2, m3])

这是非常强大的,因为它可以让你在上面构建更复杂的逻辑(例如,在列表中动态生成掩码并添加所有掩码):

import operator

cols = ['A', 'B']
ops = [np.less, np.greater]
values = [5, 5]

m = np.logical_and.reduce([op(df[c], v) for op, c, v in zip(ops, cols, values)])
m 
# array([False,  True, False,  True, False])

df[m]
   A  B  C
1  3  7  9
3  4  7  6

1-我知道我在反复强调这一点,但请容忍我。这是一个 非常 , 非常 初学者常见的错误,必须解释得非常透彻。


逻辑或

对于 df 上面,假设您希望返回A==3或B==7的所有行。

按位重载 |

df['A'] == 3

0    False
1     True
2     True
3    False
4    False
Name: A, dtype: bool

df['B'] == 7

0    False
1     True
2    False
3     True
4    False
Name: B, dtype: bool

(df['A'] == 3) | (df['B'] == 7)

0    False
1     True
2     True
3     True
4    False
dtype: bool

df[(df['A'] == 3) | (df['B'] == 7)]

   A  B  C
1  3  7  9
2  3  5  2
3  4  7  6

如果还没有,请阅读 逻辑与

或者,也可以使用

df[df['A'].eq(3) | df['B'].eq(7)]

   A  B  C
1  3  7  9
2  3  5  2
3  4  7  6

operator.or_
电话 Series.__or__ 在引擎盖下面。

operator.or_(df['A'] == 3, df['B'] == 7)
# Same as,
# (df['A'] == 3).__or__(df['B'] == 7)

0    False
1     True
2     True
3     True
4    False
dtype: bool

df[operator.or_(df['A'] == 3, df['B'] == 7)]

   A  B  C
1  3  7  9
2  3  5  2
3  4  7  6

np.logical_or
对于两种情况,使用 logical_or :

np.logical_or(df['A'] == 3, df['B'] == 7)

0    False
1     True
2     True
3     True
4    False
Name: A, dtype: bool

df[np.logical_or(df['A'] == 3, df['B'] == 7)]

   A  B  C
1  3  7  9
2  3  5  2
3  4  7  6

对于多个遮罩,请使用 logical_or.reduce :

np.logical_or.reduce([df['A'] == 3, df['B'] == 7])
# array([False,  True,  True,  True, False])

df[np.logical_or.reduce([df['A'] == 3, df['B'] == 7])]

   A  B  C
1  3  7  9
2  3  5  2
3  4  7  6

不符合逻辑

戴上口罩,比如

mask = pd.Series([True, True, False])

如果需要反转每个布尔值(以便最终结果为 [False, False, True] ),则可以使用以下任何方法。

按位 ~

~mask

0    False
1    False
2     True
dtype: bool

同样,表达式需要加括号。

~(df['A'] == 3)

0     True
1    False
2    False
3     True
4     True
Name: A, dtype: bool

这在内部称为

mask.__invert__()

0    False
1    False
2     True
dtype: bool

但不要直接使用它。

operator.inv
内部通话 __invert__ 在这个系列中。

operator.inv(mask)

0    False
1    False
2     True
dtype: bool

np.logical_not
这是numpy的变种。

np.logical_not(mask)

0    False
1    False
2     True
dtype: bool

笔记 NP逻辑_和 可以替代 np.bitwise_and , 逻辑的 具有 bitwise_or 和 logical_not 具有 invert .