2016-03-31 37 views
1

我想編寫一個函數,通過函數輸入來過濾DataFrame。在這裏,我第一次嘗試是:由變量pandas過濾

def Breakdown(file, key = None, value = None): 
    if key is not None: 
     if sampreach in ['s', 'S', 'sample', 'Sample']: 
      sampreach = sample[sample.key in [value]] 
      CountName = 'Total Count' 
     elif sampreach in ['r', 'R', 'reachable', 'Reachable']: 
      sampreach = reachable[reachable.key in [value]] 
      CountName = 'Reachable Count' 
    else: 
     if sampreach in ['s', 'S', 'sample', 'Sample']: 
      sampreach = sample 
      CountName = 'Total Count' 
     elif sampreach in ['r', 'R', 'reachable', 'Reachable']: 
      sampreach = reachable 
      CountName = 'Reachable Count' 

但我得到了以下錯誤:

AttributeError: 'DataFrame' object has no attribute 'key' 

我們的目標是能夠設置key等於列標題的名稱和value作爲名稱要篩選的值,或更好的篩選值的範圍。

在此先感謝您的幫助!脫穎而出,並可能導致你看到的錯誤

+1

您能否提供一些樣品數據和預期結果? – Alexander

回答

1

的一件事是:

sampreach = sample[sample.key in [value]] 

這可能會更好地工作,爲

sampreach = sample[sample[key].isin(value)] 

但正如評論所說,有一些信息丟失(例如,什麼是sampreach?)以及樣本數據和預期輸出,以更加明確地猜測發生了什麼。

+0

非常感謝!這工作完美。 – Josh