TLDR; Pandas 中的逻辑运算符有&、| 和~,括号(...) 很重要!
Python 的 and、or 和 not 逻辑运算符旨在与标量一起使用。因此,Pandas 必须做得更好,并覆盖位运算符以实现此功能的 vectorized(逐元素)版本。
因此,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:常见的操作是通过逻辑条件计算布尔掩码来过滤数据。 Pandas 提供三个运算符:& 用于逻辑与,| 用于逻辑或,~ 用于逻辑非。
考虑以下设置:
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 的所有行。这是通过分别计算每个条件的掩码并对它们进行与运算来完成的。
按位重载 & 运算符
在继续之前,请注意文档的这段特别摘录,其中指出
另一个常见的操作是使用布尔向量来过滤
数据。运算符是:| 代表 or,& 代表 and,~ 代表 not。 这些
必须使用括号进行分组,因为默认情况下 Python 会
将df.A > 2 & df.B < 3 等表达式计算为df.A > (2 &
df.B) < 3,而所需的计算顺序为(df.A > 2) & (df.B <
3)。
因此,考虑到这一点,可以使用按位运算符& 实现元素逻辑与:
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
括号用于覆盖位运算符的默认优先顺序,位运算符的优先级高于条件运算符< 和>。请参阅 python 文档中的Operator Precedence 部分。
如果您不使用括号,则表达式的计算将不正确。例如,如果您不小心尝试了诸如
之类的操作
df['A'] < 5 & df['B'] > 5
解析为
df['A'] < (5 & df['B']) > 5
变成这样,
df['A'] < something_you_dont_want > 5
变成了(请参阅chained operator comparison 上的 python 文档),
(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
避免括号分组
修复实际上非常简单。大多数算子都有对应的 DataFrame 绑定方法。如果单个掩码是使用函数而不是条件运算符构建的,您将不再需要按括号分组来指定评估顺序:
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
我在Dynamic Expression Evaluation in pandas using pd.eval() 中广泛记录了query 和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.logical_and,它也不需要括号分组:
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.logical_and 是 ufunc (Universal Functions),大多数 ufunc 都有 reduce 方法。这意味着如果您有多个与 AND 掩码,则使用 logical_and 更容易概括。例如,将m1 和m2 和m3 与& 进行AND 掩码,您必须这样做
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.logical_and 可以替换为np.bitwise_and,logical_or 可以替换为bitwise_or,logical_not 可以替换为invert。