2017-10-20 12 views
0

우리는 SQL 에서처럼 열을 키로 사용하여 판다에서 어떻게 연결합니까?2 열을 키로 사용하여 데이터 프레임을 연결하는 방법은 무엇입니까?

DF1

col1 col2 
a1 b1 
a2 b2 
a3 b3 
a4 b4 

DF2

내가/병합 COL3에없는 기록을 제거하기없이 COL1 =의 COL3에 그들을을 연결하려는
col3 col4 
a1  d1 
a2  d3 
a3  d3 

만에 유사한 COL 1에 SQL에서 왼쪽 조인.

안양

col1 col2 col4 
a1 b1  d1 
a2 b2  d2 
a3 b3  d3 
a4 b4  NA 
+0

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html – HFBrowning

답변

0

합니까 당신을 위해 다음과 같은 작업 :

df1 = pd.DataFrame(
    [ 
     ['a1', 'b1'], 
     ['a2', 'b2'], 
     ['a3', 'b3'], 
     ['a4', 'b4'] 
    ], 
    columns=['col1', 'col2'] 
) 

df2 = pd.DataFrame(
    [ 
     ['a1', 'd1'], 
     ['a2', 'd2'], 
     ['a3', 'd3'] 
    ], 
    columns=['col3', 'col4'] 
) 

df1 = df1.set_index('col1') 
df2 = df2.set_index('col3') 

dd = df2[df2.index.isin(df1.index)] 
# dd.index.names = ['col1'] 

df = pd.concat([df1, dd], axis=1).reset_index().rename(columns={'index': 'col1'}) 

# Output 
    col1 col2 col4 
0 a1 b1  d1 
1 a2 b2  d2 
2 a3 b3  d3 
3 a4 b4  NaN