df1数据如下
df2数据如下
连接查询代码 -1
import pandas as pd
df1 = pd.DataFrame({'id':['1001','1002','1003','1004'],
'name':['Hu','Dotu','Evp','Swe']})
df2 = pd.DataFrame({'id':['1001','1001','1003','1004', '1003'],
'course':['c1','c2','c3','c2','c1'],
'score':[100, 98, 64, 84, 69]})
result = pd.merge(df1, df2, how='right',on = 'id')
print('========= result =========') # 效果如下
print(result)
运行结果
========= result =========
id name course score
0 1001 Hu c1 100
1 1001 Hu c2 98
2 1003 Evp c3 64
3 1004 Swe c2 84
4 1003 Evp c1 69
连接查询代码 -2
import pandas as pd
df1 = pd.DataFrame({'id':['1001','1002','1003','1004'],
'name':['Hu','Dotu','Evp','Swe']})
df2 = pd.DataFrame({'id':['1001','1001','1003','1004', '1003'],
'course':['c1','c2','c3','c2','c1'],
'score':[100, 98, 64, 84, 69]})
result = pd.merge(df1, df2, how='left',on = 'id')
print('========= result =========') # 效果如下
print(result)
运行结果
id name course score
0 1001 Hu c1 100.0
1 1001 Hu c2 98.0
2 1002 Dotu NaN NaN
3 1003 Evp c3 64.0
4 1003 Evp c1 69.0
5 1004 Swe c2 84.0