用pandas实现表格的内连接、外连接、左连接和右连接

基于pd.merge函数,实现两个表格的内连接、外连接、左连接和右连接,代码示例如下


表格1

import pandas as pd
df1 = pd.DataFrame({'year':[2020,2020,2021,2021,2022], 
                    'company':['apple','google','apple','google','apple'], 
                    'profit':[100,200,150,300,180]})
df1


表格2

df2 = pd.DataFrame({'year':[2020,2020,2021,2021,2021], 
                    'company':['apple','google','apple','google','tesla'], 
                    'employee':[20000,50000,22000,60000,30000]})
df2


内连接

pd.merge(df1,df2,how='inner',on=['year','company'])


外连接

pd.merge(df1,df2,how='outer',on=['year','company'])


左连接

pd.merge(df1,df2,how='left',on=['year','company'])


右连接

pd.merge(df1,df2,how='right',on=['year','company'])

posted @ 2023-09-18 18:13  Bill_H  阅读(394)  评论(0编辑  收藏  举报