【问题标题】:using 'OR' to select data in pandas使用“或”选择 pandas 中的数据
【发布时间】:2012-11-14 09:15:45
【问题描述】:

我有一个值数据框,我想探索异常值的行。我在下面编写了一个函数,可以使用groupby().apply() 函数调用它,它适用于高值或低值,但是当我想将它们组合在一起时会产生错误。我以某种方式弄乱了布尔 OR 选择,但我只能使用 & 找到选择标准的文档。任何建议将不胜感激。

扎克cp

df = DataFrame( {'a': [1,1,1,2,2,2,2,2,2,2], 'b': [5,5,6,9,9,9,9,9,9,20] } )

#this works fine
def get_outliers(group):
    x = mean(group.b)
    y = std(group.b)
    top_cutoff =    x + 2*y
    bottom_cutoff = x - 2*y
    cutoffs = group[group.b > top_cutoff]
    return cutoffs

#this will trigger an error
def get_all_ outliers(group):
    x = mean(group.b)
    y = std(group.b)
    top_cutoff =    x + 2*y
    bottom_cutoff = x -2*y
    cutoffs = group[(group.b > top_cutoff) or (group.b < top_cutoff)]
    return cutoffs

#works fine    
grouped1 = df.groupby(['a']).apply(get_outliers)
#triggers error
grouped2 = df.groupby(['a']).apply(get_all_outliers)

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您需要使用| 而不是orandor 运算符在 Python 中是特殊的,不能与 numpy 和 pandas 等试图在集合中逐元素应用它们的东西很好地交互。因此,对于这些上下文,他们重新定义了“按位”运算符&amp;| 来表示“与”和“或”。

    【讨论】:

      猜你喜欢
      • 2017-03-08
      • 2019-12-02
      • 2012-07-28
      • 1970-01-01
      • 2017-08-10
      • 1970-01-01
      • 2015-03-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多