我有一些代码在 cron 上(通过 kubernetes)运行了几个月。
昨天,我的部分代码无法正常工作:
突然间,这个声明不是“真”的(df_temp 和 df_temp4 中都有数据:
if ( len(df_temp > 0) & len(df_temp4 > 0)):
print "HERE"
然而,这有效:
if ( len(df_temp > 0) and len(df_temp4 > 0)):
print "HERE"
是否有某种代码推送会导致此更改?由于我已经运行这段代码几个月了,所以不确定什么会导致这条语句突然失败。
最佳答案
len(df_temp > 0)
和 len(df_temp4 > 0)
可能不符合您的预期。 pandas DataFrame 的比较运算符返回按元素计算的结果,这意味着它们创建一个 bool 值 DataFrame,其中每个值指示 DataFrame 中的相应值是否大于零:
>>> import pandas as pd
>>> df = pd.DataFrame({'a': [-1,0,1], 'b': [-1,0,1]})
>>> df
a b
0 -1 -1
1 0 0
2 1 1
>>> df > 0
a b
0 False False
1 False False
2 True True
所以df
的len
与df>0
的len
是一样的:
>>> len(df)
3
>>> len(df > 0)
3
difference between "&" and "and"
它们的含义不同:
&
是 bitwise and and
是 logical and (和短路)由于您专门询问了 pandas(假设至少一个操作数是 NumPy 数组、pandas Series 或 pandas DataFrame):
&
也指按元素“按位与”。 and
,而是必须使用一个函数,即numpy.logical_and
。 .更多解释可以引用"Difference between 'and' (boolean) vs. '&' (bitwise) in python. Why difference in behavior with lists vs numpy arrays?"
not sure what would cause this statement to fail all of a sudden.
您没有提供“失败”,也没有提供预期的行为,所以很遗憾,我无法在这方面为您提供帮助。
关于python - Pandas 中 "&"和 "and"之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54315627/