【问题标题】:Pandas logical operator & does not work but 'and' worksPandas 逻辑运算符 & 不起作用,但 'and' 起作用
【发布时间】:2019-04-29 09:01:09
【问题描述】:

我在 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。

【问题讨论】:

  • 你可能想要st1 == 'A' not the =`
  • 对不起,这是我做的...错误仍然存​​在。

标签: python pandas


【解决方案1】:

&and 在 Python 中不是一回事——& 是位运算符,and 是逻辑运算符。请参阅以前的答案herehere,以及 Wikipedia page 关于按位运算。

在 pandas 中,您可以在选择 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

【讨论】:

    猜你喜欢
    • 2020-09-03
    • 1970-01-01
    • 2017-08-02
    • 1970-01-01
    • 2015-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多