Pandas中“&”和“and”的区别

2024-05-19 10:22:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些代码在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"

是否有某种代码推送会导致这种变化?因为我已经运行了几个月的代码,不确定是什么会导致这个语句突然失败


Tags: and数据代码dflenifhere语句
3条回答

从逻辑上讲,这两种说法是不同的。 政府;表示按位运算符。 AND表示逻辑AND

他们有完全不同的行为
当您使用and时,您是在比较布尔值,但当您使用&时,您是在使用逻辑and元素。我建议您阅读此完整答案以了解更多信息。
Logic operator for boolean indexing in Pandas

import pandas as pd

dfa = pd.DataFrame([True, False])
dfb = pd.DataFrame([False, False])

print(dfa & dfb)
#    0
# 0  False
# 1  False

print(dfa and dfb)
# ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

len(df_temp > 0)len(df_temp4 > 0)可能没有达到您期望的效果。带有DataFrames的比较运算符返回按元素的结果,这意味着它们创建一个布尔数据帧,其中每个值指示DataFrames中的对应值是否大于零:

>>> 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

因此{}的{}与{}的{}相同:

>>> len(df)
3
>>> len(df > 0)
3

difference between "&" and "and"

它们的含义不同:

由于您特别询问了熊猫(假设至少有一个操作数是NumPy数组、熊猫系列或熊猫数据帧):

  • &也指按元素的“按位and”
  • pandas的元素级“逻辑and”不是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.

您没有提供“失败”或预期的行为,因此很遗憾,我无法在这方面帮助您

相关问题 更多 >

    热门问题