【问题标题】:Using logical operators in building a Pandas DataFrame在构建 Pandas DataFrame 时使用逻辑运算符
【发布时间】:2013-10-25 05:12:54
【问题描述】:

我有两个 sn-ps 的 pandas 代码,我认为它们应该是等效的,但第二个没有达到我的预期。

# snippet 1
    data = all_data[[((np.isfinite(all_data[self.design_metric][i]) 
                    and all_data['Source'][i] == 2)) 
                    or ((np.isfinite(all_data[self.actual_metric][i]) 
                    and all_data['Source'][i] != 2))
                    for i in range(len(all_data))]]


# snippet 2
    data = all_data[(all_data['Source'] == 2 &
                    np.isfinite(all_data[self.design_metric])) |
                    (all_data['Source'] != 2 &
                    np.isfinite(all_data[self.actual_metric]))]

每个部分(例如 all_data['Source'] == 2 )都按照我的预期做,但似乎我对逻辑运算符做错了,因为最终结果与列表理解版本的结果不同。

【问题讨论】:

    标签: python pandas logical-operators


    【解决方案1】:

    & 运算符比==(或任何比较运算符)绑定得更紧密。见the documentation。一个更简单的例子是:

    >>> 2 == 2 & 3 == 3
    False
    

    这是因为它被分组为2 == (2 & 3) == 3,然后调用了比较链接。这就是您的情况。您需要在每个比较前后加上括号。

     data = all_data[((all_data['Source'] == 2) &
                    np.isfinite(all_data[self.design_metric])) |
                    ((all_data['Source'] != 2) &
                    np.isfinite(all_data[self.actual_metric]))]
    

    注意==!= 比较周围的额外括号。

    【讨论】:

      【解决方案2】:

      除了优先级之外,AND 和 & 运算符之间也有区别,第一个是布尔值,后者是二进制位。此外,您必须了解布尔表达式。

      请参阅以下 sn-p 中的示例:

      逻辑表达式

      >>> 1 and 2
      1
      
      >>> '1' and '2'
      '1'
      
      >>> 0 == 1 and 2 == 0 or 0
      0
      

      位运算符

      >>> 1 & 2
      0
      
      >>> '1' & '2'
      Traceback (most recent call last):
        ...
      TypeError: unsupported operand type(s) for &: 'str' and 'str'
      
      >>> 0 == 1 & 2 == 0 | 0
      True
      

      【讨论】:

        猜你喜欢
        • 2021-03-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-20
        相关资源
        最近更新 更多