熊猫逻辑运算符&不起作用,但“ and”起作用

时间:2018-11-27 15:18:46

标签: python pandas

我对熊猫中的逻辑运算符有疑问。 如果我尝试:

list1=['x','y']
if st1=='A' & str2 not in list1: #do stuff

我得到:

unsupported operand type(s) for &: 'str' and 'bool'", u'occurred at index 0

但这行得通:为什么?

if st1=='A' and str2 not in list1: #do stuff

我所做的就是将&更改为and。

1 个答案:

答案 0 :(得分:3)

&and在Python中不是同一件事-&是按位运算符,and是逻辑运算符。有关按位操作,请参见先前的答案herehere,以及维基百科page

在熊猫中,选择DataFrame的子集时,可以使用&进行逻辑操作,例如:

df = pd.DataFrame(data={"col1":[1,2,3], "col2":[2,3,4]})
df[(df["col1"]>1) & (df["col2"]<4)] # Selects second row based on boolean criteria
相关问题