2013-06-11 219 views
2

我有熊貓系列,我們會打電話給我想使用作爲篩選一個DF其中approved_fields:過濾熊貓據幀

approved_field(['Field1','Field2','Field3')] 

df 
    Field 
0 Field1 
1 Field4 
2 Field2 
3 Field5 
4 Field2 

應用approved_field過濾器後,產生的DF應該像:

Field 
0 Field1 
1 Field2 
2 Field2 

謝謝!

回答

5

您可以使用isin和布爾索引:

>>> import pandas as pd 
>>> df = pd.DataFrame({"Field": "Field1 Field4 Field2 Field5 Field2".split()}) 
>>> approved_fields = "Field1", "Field2", "Field3" 
>>> df['Field'].isin(approved_fields) 
0  True 
1 False 
2  True 
3 False 
4  True 
Name: Field, dtype: bool 
>>> df[df['Field'].isin(approved_fields)] 
    Field 
0 Field1 
2 Field2 
4 Field2 
3

請注意,您在您的預期解決方案指數掉

In [16]: approved_field = ['Field1','Field2','Field3'] 

In [17]: df = DataFrame(dict(Field = ['Field1','Field4','Field2','Field5','Field2'])) 

In [18]: df 
Out[18]: 
    Field 
0 Field1 
1 Field4 
2 Field2 
3 Field5 
4 Field2 

In [19]: df[df.Field.isin(approved_field)] 
Out[19]: 
    Field 
0 Field1 
2 Field2 
4 Field2 
+0

感謝傑夫,我在OP – ChrisArmstrong

+0

正確答案修正了這個,DSM只打你2分鐘! – ChrisArmstrong

+0

這就是他們對兔子和兔子說的話:) – Jeff