The python DataFrame merge function merges two DataFrames (connected with sql)

pd.merge(df1,df2,on="class_id",how="right")

Create two dataframes

temp_dict1 = [{"id":1,"name":"cyw","age":20,"class_id":1},
             {"id":2,"name":"xiaogang","age":18,"class_id":2},
            {"id":2,"name":"老王","age":18,"class_id":3},
            {"id":2,"name":"张三","age":18,"class_id":2},
            {"id":2,"name":"李四","age":18,"class_id":3},
            {"id":2,"name":"赵子龙","age":18,"class_id":4}]

temp_dict2 = [{"class_id":1,"class":"一班"},
             {"class_id":2,"class":"二班"},
              {"class_id":3,"class":"三班"},
              {"class_id":4,"class":"四班"},
              {"class_id":5,"class":"五班"}
            ]
classes = pd.DataFrame(temp_dict2)
students = pd.DataFrame(temp_dict1)

Inner join (take the intersection of two tables)

pd.merge(df1,df2,on="class_id") 

equivalent to in sql

select * from students inner join classes on students.class_id = classes.class_id;

Left join (get all the records in the left table, even if there is no matching record in the right table, the unmatched data will be replaced by NAN)

pd.merge(df1,df2,on="class_id",how="left")
#等价于pd.merge(df1,df2,left_on="class_id",right_on="class_id",how="left")

quite in sql

select * from students left join classes on students.class_id = classes.class_id;

 

 Right join (contrary to LEFT JOIN, used to get all the records in the right table, even if there is no corresponding matching record in the left table, the unmatched data will be replaced by NAN) 

pd.merge(df1,df2,on="class_id",how="right")
#等价于pd.merge(df1,df2,left_on="class_id",right_on="class_id",how="right")

quite in sql

select * from students right join classes on students.class_id = classes.class_id;

Guess you like

Origin blog.csdn.net/weixin_49583390/article/details/120015719