通过python实现Sql中的表连接操作
一、merg实现表连接
数据准备:
import pandas as pd
import numpy as np
left = pd.DataFrame({'key':['K0','K1','K2','K3'],
'A':['A0','A1','A2','A3'],
'B':['B0','B1','B2','B3']
})
right = pd.DataFrame({'key':['K0','K11','K2','K31'],
'C':['C0','C1','C2','C3'],
'D':['D0','D1','D2','D3']
})
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
输出结果:
1、单条件连接:merge
内连接:
# how参数不写 默认是内连接
pd.merge(left,right,on = ['key'])
pd.merge(left,right,on = ['key'],how='inner')
- 1
- 2
- 3
输出结果:
外连接(全连接):
# 外连接
pd.merge(left,right,on = ['key'],how='outer')
- 1
- 2
输出结果:
左连接:
# 左连接
pd.merge(left,right,on = ['key'],how='left')
- 1
- 2
输出结果:
右连接:
# 右连接
pd.merge(left,right,on = ['key'],how='right')
- 1
- 2
输出结果:
2、多条件连接:merge
数据准备:
#多条件关联
left1 = pd.DataFrame({'key1':['K0','K0','K1','K2'],
'key2':['K0','K1','K0','K1'],
'A':['A0','A1','A2','A3'],
'B':['B0','B1','B2','B3']
})
right1 = pd.DataFrame({'key1':['K0','K1','K1','K2'],
'key2':['K0','K0','K0','K0'],
'C':['C0','C1','C2','C3'],
'D':['D0','D1','D2','D3']
})
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
输出结果:
内连接:
# 内连接 ,how 参数不写默认是内连接
pd.merge(left1,right1,on=['key1','key2'])
pd.merge(left1,right1,on=['key1','key2'],how = 'inner')
- 1
- 2
- 3
输出结果:
外连接(全连接):
# 外连接
pd.merge(left1,right1,on=['key1','key2'],how= 'outer')
- 1
- 2
输出结果:
左连接:
# 左连接
pd.merge(left1,right1,on=['key1','key2'],how= 'left')
- 1
- 2
输出结果:
右连接:
# 右连接
pd.merge(left1,right1,on=['key1','key2'],how= 'right')
- 1
- 2
输出结果:
二、concat实现表连接
数据准备:
df1 = pd.DataFrame(np.ones((3,4))*0,columns= ['a','b','c','d'],index=(1,2,3))
df2 = pd.DataFrame(np.ones((3,4))*11,columns= ['b','c','d','e'],index=(2,3,4))
- 1
- 2
输出结果:
1、行连接(横向连接):
全连接:
pd.concat([df1,df2],axis=1)
- 1
输出结果:
左连接:
pd.concat([df1,df2],axis=1,join_axes=[df1.index])
- 1
输出结果:
右连接:
pd.concat([df1,df2],axis=1,join_axes=[df2.index])
- 1
输出结果:
2、列连接(纵向连接):
两种方法实现:concat/append
方法1、concat
pd.concat([df1,df2],axis=0)
- 1
输出结果:
调整索引的顺序:
pd.concat([df1,df2],axis=0,ignore_index =True)
- 1
输出结果:
方法2、append
df1.append(df2,ignore_index=True)
- 1
输出结果:
三、merge和concat的区别:
1、merge默认是内连接,concat默认是外连接
2、merge的参数how有left/right/inner/outer,concat的参数axis有0/1(0:列,1:行),通过concat实现左/右连接主要是跟参数写的位置有关
3、merge合并的范围广泛,可以通过索引/列关联,concat合并的范围小,只支持索引的合并