【问题标题】:Logical operation on two columns of a dataframe数据框两列的逻辑运算
【发布时间】:2016-01-27 17:10:55
【问题描述】:

在 pandas 中,我想创建一个计算列,它是对另外两列的布尔运算。

在 pandas 中,将两个数值列相加很容易。我想用逻辑运算符AND 做类似的事情。这是我的第一次尝试:

In [1]: d = pandas.DataFrame([{'foo':True, 'bar':True}, {'foo':True, 'bar':False}, {'foo':False, 'bar':False}])

In [2]: d
Out[2]: 
     bar    foo
0   True   True
1  False   True
2  False  False

In [3]: d.bar and d.foo   ## can't
...
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

所以我猜逻辑运算符的工作方式与 pandas 中的数字运算符不太一样。我尝试按照错误消息的建议执行操作并使用bool():

In [258]: d.bar.bool() and d.foo.bool()  ## spoiler: this doesn't work either
...
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

我找到了一种方法,将布尔列转换为int,将它们加在一起并作为布尔值进行评估。

In [4]: (d.bar.apply(int) + d.foo.apply(int)) > 0  ## Logical OR
Out[4]: 
0     True
1     True
2    False
dtype: bool

In [5]: (d.bar.apply(int) + d.foo.apply(int)) > 1  ## Logical AND
Out[5]: 
0     True
1    False
2    False
dtype: bool

这很复杂。有没有更好的办法?

【问题讨论】:

    标签: pandas boolean-operations


    【解决方案1】:

    是的,有更好的方法!只需使用 & 元素逻辑和运算符:

    d.bar & d.foo
    
    0     True
    1    False
    2    False
    dtype: bool
    

    【讨论】:

    【解决方案2】:

    另外,还有一个你可以乘以 AND 或相加为 OR。没有您所做的转换和额外比较。

    AND 操作:

    d.foo * d.bar
    

    或运算:

    d.foo + d.bar 
    

    【讨论】:

      【解决方案3】:
      d[(d['bar']) & (d['foo'])] 
      

      【讨论】:

      • 虽然此代码可以解决问题,including an explanation 说明如何以及为什么解决问题将真正有助于提高您的帖子质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提问的人。请edit您的回答添加解释并说明适用的限制和假设。
      猜你喜欢
      • 1970-01-01
      • 2021-12-03
      • 1970-01-01
      • 1970-01-01
      • 2017-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多