熊猫中布尔索引的逻辑运算符
重要的是要认识到,您不能使用任何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
).