有好几次想要用python实现SQL的join查询功能,找了好多教程,都没有给出完整的sql 中 七种经典join查询。而且有的博客给出的merge参数也不完整。对于未查过模块原文档的同学真是挠头。
正常的inner outer left right 四种表连接查询都很容易理解,关键在于左连接只包含左表,右链接只包含右表两种查询需求,而merge中的indicator参数返回结果,就可以轻松实现了。
需要注意代码中给出的并非最终查询结果,最好伪代码和注释有提到,需要对’_merge’ 进行筛选判断。
both表示左右表共有的,
left_only
right_only 如同译文的意思。可以找几个真实案例感受下,也是很好用。
寄代码、图如下。有问题可以讨论哦…
import numpy as np
import pandas as pd
sst = 'abcdefghiuvwxyzsdfd'
cola = []
for i in sst:
cola.append(i)
np.random.seed(10)
x1 = np.random.randint(1,100,len(cola))
colb = list(set(cola))
x2 = np.random.randn(len(colb))*10
data01 = pd.DataFrame({'type':cola,
'val1':x1})
data02 = pd.DataFrame({'type':colb,
'val2':x2})
df1 = pd.merge(data01,data02,left_on='type',right_on='type' ,how='inner',indicator=True,)
# SQL 中的 join 查询。交集
print(len(df1))
df2 = pd.merge(data01,data02,left_index=True,right_index=True ,how='left',indicator=True,)
# SQl 中的 left join where right_index is null,同于df2[df2['_merge'] == ‘both’]
print(len( df2[df2['_merge'] == 'both'] ))
df3 = pd.merge(data01,data02,left_index=True,right_index=True ,how='right',indicator=True,)
# SQl 中的 right join where left_index is null, 同于df3[df3['_merge'] == 'both']
print(len( df3[df3['_merge'] == 'both'] ))
output:
19
16
16
df1输出结果:
等同于SQL 的 inner join 查询结果
df2输出结果:
df2._merge == ‘both’
等同于SQL 的 left join where b.col is null
df3输出结果:
等同于SQL 中的 right join where a.col is null