正确使用 `df.query()` 处理多个条件的方法是什么?

huangapple go评论70阅读模式
英文:

What is the correct way to use df.query() with multiple conditions?

问题

Based on the pandas documentation for query, it's possible to use both and/or and &/| operators in query statements with multiple conditions. The documentation states that & and | (bitwise) operators have the same precedence as and and or. In practice, both can be used, and the choice of operator does not change the result. Here's an example:

import numpy as np
import pandas as pd

df = pd.DataFrame(data=np.random.randn(5,2), columns=['A','B'])
df['names'] = list('ABCDE')

query1 = df.query("A > -1 and B < 1 or 'B' in names")

query2 = df.query("A > -1 & B < 1 | 'B' in names")

query1.equals(query2)

Both query1 and query2 in this example will yield the same results.

英文:

Based on the pandas documentation for query, I do not understand whether it is correct to use and/or or &amp;/| in a query statement with multiple conditions.

Is there a situation when using both bitwise and boolean operators might be necessary? Is there a best practice for when to use which?

The documentation states:

For example, the &amp; and | (bitwise) operators have the precedence of their boolean cousins, and and or, but the practical implications are not clear to me.

I have found accepted answers where users use either bitwise or boolean operators, in this case the answer using query contains and in first case and &amp; in second, getting the same results.

Here is an example where the choice of operator does not change the result:

import numpy as np
import pandas as pd

df = pd.DataFrame(data=np.random.randn(5,2), columns=[&#39;A&#39;,&#39;B&#39;])
df[&#39;names&#39;] = list(&#39;ABCDE&#39;)

query1 = df.query(&quot;A &gt; -1 and B &lt; 1 or &#39;B&#39; in names&quot;)

query2 = df.query(&quot;A &gt; -1 &amp; B &lt; 1 | &#39;B&#39; in names&quot;)

query1.equals(query2)

Thanks for help.

答案1

得分: 3

所有操作都返回一个布尔值(true/false)掩码,所以无论您使用位运算符还是逻辑运算符都没关系。然而,如果您的数字不是0/1(True/False),结果是不同的:

>>> 0 & 1  # 与 False & True 相同
0  # False

>>> 0 and 1  # 与 False and True 相同
0  # False

>>> 2 & 3
2

>>> 2 and 3
3
英文:

All operations return a boolean (true/false) mask, so it doesn't matter whether you use a bitwise or logical operator. However the result is not the same if your numbers are not 0/1 (True/False):

&gt;&gt;&gt; 0 &amp; 1  # same as False &amp; True
0  # False

&gt;&gt;&gt; 0 and 1  # same as False and True
0  # False

&gt;&gt;&gt; 2 &amp; 3
2

&gt;&gt;&gt; 2 and 3
3

huangapple
  • 本文由 发表于 2023年5月11日 17:28:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76226121.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定