如何连接使用2列作为键的数据框?

问题描述:

我如何在熊猫中使用列作为键来连接,就像我们在sql中一样?如何连接使用2列作为键的数据框?

DF1

col1 col2 
a1 b1 
a2 b2 
a3 b3 
a4 b4 

DF2

col3 col4 
a1  d1 
a2  d3 
a3  d3 

我想合并/它们串联在col1 = COL3没有摆脱不在COL3的记录,但在山坳1.类似sql中的左连接。

DF

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

为您做了以下工作:

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