2015-11-18 76 views
1

與此類似,但不一樣的:Selecting rows - based on a list - from a DF with duplicated columns大熊貓:選擇行 - 基於列表 - DF與重複行標籤

我有兩個DFS:

df1 = pd.DataFrame({'total': [25, 45, 75, 36, 45]}, 
        index=['base', 'c', 'd', 'base', 'e']) 
     total 
base  25 
c  45 
d  75 
base  36 
e  45 

df2 = pd.DataFrame({'type': ['rc', 'rc', 'c%', 'c%', 'pp%']}, 
        index=['base', 'c', 'd', 'base', 'e']) 

    type 
base rc 
c  rc 
d  c% 
base c% 
e  pp% 

我想要得到的行,其中值是來自df1的df2內的'c%'和/或'pp%'。

這裏是我正在做

keep = df2[df2['type'].isin(['c%', 'pp%'])].index 
Index([u'd', u'base', u'e'], dtype='object') 

df1.loc[keep] 
     total 
d  75 
base  25 
base  36 
e  45 

「基地25」不應該有,但因爲我使用的標籤,我明白爲什麼它的存在。

期望的結果:

 total 
d  75 
base  36 
e  45 

我怎樣才能改變我的代碼來處理這個問題?

回答

2
In [9]: 

(df2['type'] == 'c%') | (df2['type'] == 'pp%') 
Out[9]: 
base False 
c  False 
d  True 
base  True 
e  True 
Name: type, dtype: bool 

In [8]: 
df1[(df2['type'] == 'c%') | (df2['type'] == 'pp%')] 
Out[8]: 
    total 
d  75 
base 36 
e  45 
+0

如何重置索引?因爲過濾可能不基於布爾值。 –

+0

是否要根據「真」或「假」值或基於「索引」進行切片? –

+0

指數。道歉的真實和錯誤只是一個例子,更容易解釋。 –

1

這是你想要的嗎?

In [54]: df1[['total']][df2['bool']=='True'] 
Out[54]: 
     total 
d  75 
base  36 
e  45