英文:
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 &
/|
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 &
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 &
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=['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)
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):
>>> 0 & 1 # same as False & True
0 # False
>>> 0 and 1 # same as False and True
0 # False
>>> 2 & 3
2
>>> 2 and 3
3
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论