2012-11-26 33 views
1

我有一個值的數據框,我想探索異常行。我寫了一個函數,它可以用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) 

回答

2

您需要使用|而不是orandor運算符在Python中是特殊的,並且不會像numpy和pandas那樣嘗試將它們應用於整個集合的元素。因此,對於這些上下文,他們已將「按位」運算符&|重新定義爲「和」和「或」。

+0

感謝BrenBarn。奇蹟般有效。 – zach