2016-06-20 4 views
1

안녕하세요 두 개의 데이터 프레임이 있습니다. 그들은 공통 색인을 가지고 있습니다. 두 개의 원래 날짜 프레임을 공통 색인 만 포함 된 두 개의 새로운 날짜 프레임으로 변환하고 싶습니다. 이 일을 성취하도록 도와 주시겠습니까? 다음은 그 예입니다.공통 색인에 따라 두 개의 데이터 프레임 필터링

 df1 = pd.DataFrame({'one' : pd.Series([1,3,5], index=['a', 'b', 'c']), 
    ....:     'two' : pd.Series([2,4,6], index=['a', 'b', 'c']), 
    ....:     'three' : pd.Series([-4,-3,-2], index=['a','b', 'c'])}); 
df2=pd.DataFrame({'x' : pd.Series([1,3,5], index=['b', 'c', 'd']), 
    ....:     'y' : pd.Series([2,4,6], index=['b', 'c', 'd']), 
    ....:     'z' : pd.Series([-3,-2,-1], index=['b', 'c', 'd'])}); 
print(df1) 
print(df2) 

그래서 df1과 df2는 다음과 같습니다.

one three two 
a 1  -4 2 
b 3  -3 4 
c 5  -2 6 
    x y z 
b 1 2 -3 
c 3 4 -2 
d 5 6 -1 

내가

one three two 

b 3  -3 4 
c 5  -2 6 
    x y z 
b 1 2 -3 
c 3 4 -2 

답변

0

내가 boolean indexing과 함께 Index.intersection을 사용 :

In [73]: mask = df1.index.intersection(df2.index) 

In [77]: df1 = df1.ix[mask] 

In [78]: df2 = df2.ix[mask] 

In [79]: df1 
Out[79]: 
    one three two 
b 3  -3 4 
c 5  -2 6 

In [80]: df2 
Out[80]: 
    x y z 
b 1 2 -3 
c 3 4 -2 

또는 isin() fution :

In [81]: df1[df1.index.isin(df2.index)] 
Out[81]: 
    one three two 
b 3  -3 4 
c 5  -2 6 

In [82]: df2[df2.index.isin(df1.index)] 
Out[82]: 
    x y z 
b 1 2 -3 
c 3 4 -2 
0

당신은 .join()을 사용할 수 있습니다처럼이 될보고 싶다 :

df1.join(df2, how='inner')[df1.columns] 

    one three two 
b 3  -3 4 
c 5  -2 6 
관련 문제