df1: Subjects Grades Marks 0 Physics A 95 1 Chemistry C 72 2 Mathematics B 88 df2: Subjects Marks Remarks 0 Biology 85 Very Good 1 Chemistry 72 Good 2 Literature 68 Fair
As we can see the first DataFrame has the columns Subjects, Grades, and Marks. And the second DataFrame has the columns Subjects, Marks, and Remarks. We will merge these two DataFrames on the Subjects column.
import pandas dict1 = {"Subjects": ["Physics", "Chemistry", "Mathematics"], "Grades": ["A", "C", "B"], "Marks": [95, 72, 88]} df1 = pandas.DataFrame(dict1) print("df1: \n", df1) dict2 = {"Subjects": ["Biology", "Chemistry", "Literature"], "Marks": [85, 72, 68], "Remarks": ["Very Good", "Good", "Fair"]} df2 = pandas.DataFrame(dict2) print("df2: \n", df2) df3 = pandas.merge(df1, df2, how="inner", on="Subjects") print("After inner join: \n", df3)
Here, we are performing an inner join operation on the Subjects column. The Subjects column is present in both the DataFrames. When we do an inner join operation, only the rows that have the same values in both the DataFrames are taken. Rest of the rows are ignored.
So, in our case, the row that has the value “Chemistry” in the Subjects column is common in both the DataFrames. So, the output of the inner join operation will be the following:
df1: Subjects Grades Marks 0 Physics A 95 1 Chemistry C 72 2 Mathematics B 88 df2: Subjects Marks Remarks 0 Biology 85 Very Good 1 Chemistry 72 Good 2 Literature 68 Fair After inner join: Subjects Grades Marks_x Marks_y Remarks 0 Chemistry C 72 72 Good
Merging DataFrames using a left join
In the case of the left join operation, all the rows from the left DataFrame are taken. And only the rows that have common …






0 Comments